Hi Stack Exchange Community,
I'm looking to understand how to insert an IF statement inside the code below:
$html.= '<span class="cat">In <a href="'. $typeLink . '">' . $terms_string . '</a></span>';
Essentially, I would like to insert a glyph just before the hyperlink that changes based on the value of $terms_string (using IF and ELSEIF). I thought the line below might be close to what I need, but I'm unsure if I'm accurately switching between PHP and HTML (definitely user error, but is it a syntax error?).
$html.= '<span class="cat">In '. if($terms_string === "Articles") { glyph HTML code }; .' <a href="'. $typeLink . '">' . $terms_string . '</a></span>';
Any insights would be greatly appreciated.
Hi Stack Exchange Community,
I'm looking to understand how to insert an IF statement inside the code below:
$html.= '<span class="cat">In <a href="'. $typeLink . '">' . $terms_string . '</a></span>';
Essentially, I would like to insert a glyph just before the hyperlink that changes based on the value of $terms_string (using IF and ELSEIF). I thought the line below might be close to what I need, but I'm unsure if I'm accurately switching between PHP and HTML (definitely user error, but is it a syntax error?).
$html.= '<span class="cat">In '. if($terms_string === "Articles") { glyph HTML code }; .' <a href="'. $typeLink . '">' . $terms_string . '</a></span>';
Any insights would be greatly appreciated.
Share Improve this question edited Jan 27, 2020 at 20:56 Howdy_McGee♦ 20.9k24 gold badges91 silver badges177 bronze badges asked Jan 27, 2020 at 20:45 imcamelliottimcamelliott 132 bronze badges1 Answer
Reset to default 2This is more general PHP than anything WordPress specific.
String concatenation occurs whenever you combining two stings with the .
operator. During string concatenation some basic PHP keywords will not apply and you'll need to use the shorthand equivalent instead. In this case you can use the ternary (conditional) operator
$html.= '<span class="cat">In '. ( $terms_string === "Articles" ) ? 'glyph HTML code' : '' .' <a href="'. $typeLink . '">' . $terms_string . '</a></span>';
A better, more readable format may be breaking up the HTML output into multiple strings:
$html.= '<span class="cat">In ';
if( "Articles" == $terms_string ) {
$html .= 'glyph HTML code';
}
$html .= '<a href="'. $typeLink . '">' . $terms_string . '</a></span>';