How to Add a PHP if Statement Into a HTML String
Get the solution ↓↓↓I want to add the checked attribute (checked="checked") to an input if the value of some user meta data is true. But I don't know the correct syntax to do this when working within a HTML string. Here's my current syntax:
$html = '' .
'<h3>User Committees</h3>' .
'<table class="form-table">' .
'<tr>' .
'<td>' .
'<label>' .
'<input type="checkbox" name="conference_&_sponsorship" value="1" ' . if ( get_user_meta($user->ID, 'conference_&_sponsorship', true) == 'true') { 'checked' } . '>' .
'Conference & Sponsorship' .
'</label>' .
'</td>' .
'</tr>' .
'</table>';
echo $html;
Answer
Solution:
Ternary operator will help you:
$html = '' .
'<label>' .
'<input type="checkbox" name="conference_&_sponsorship" value="1" ' . ( get_user_meta($user->ID, 'conference_&_sponsorship', true) == 'true' ? 'checked' : '' ) . '>' .
'Conference & Sponsorship' .
'</label>';
echo $html;
Answer
Solution:
This is PHP (not Sparta), so just use a multiline string, I get goosebumps seeing your code :)
$checked = get_user_meta($user->ID, 'conference_&_sponsorship', true) ? 'checked' : '';
$html = '
<h3>User Committees</h3>
<table class="form-table">
<tr>
<td>
<label>
<input type="checkbox" name="conference_&_sponsorship" value="1" '.$checked.'">
Conference & Sponsorship
</label>
</td>
</tr>
</table>
';
echo $html;
Answer
Solution:
You can always seperate it like this:
$html = '' .
'<h3>User Committees</h3>' .
'<table class="form-table">' .
'<tr>' .
'<td>' .
'<label>' .
'<input type="checkbox" name="conference_&_sponsorship" value="1" ';
if ( get_user_meta($user->ID, 'conference_&_sponsorship', true) == 'true') { $html .= 'checked'; }
$html .= '>' .
'Conference & Sponsorship' .
'</label>' .
'</td>' .
'</tr>' .
'</table>';
echo $html;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: attempt to read property "id" on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.