Crystal ball suggested that we are talking about Wordpress. The post_class()
method prints the post classes (just like echo "что-то";
), and does not return a value (like return "что-то";
).
Therefore, to compose a string in a variable, you need a related method get_post_class()
. But it returns not a formatted string, like the one printed by the post_class()
method, but returns an array of post classes. And this array must also be assembled into a string. Like that:
$html .= sprintf('<article id="post-%s" class="%s">' get_the_ID(), implode(',', get_post_class()) // склеит массив через запятую );
Same with your code snippet. If you want to put it in a variable, and not to display it, you need WordPress methods that do not display, but return values.
Instead of the_permalink()
- get_permalink()
. Instead of echo
, concatenate values to code. Like that:
$tmpl = <<<EOFHTML <div class="titl2"> <a href="%s"> <p>%s</p> </a> </div> EOFHTML; $map_location = get_field( 'adress' ); // опечатка? Может, address? $address = explode( ', ', $map_location['address'] ); $html .= sprintf( $tmpl, get_permalink(), $address[0] . ' ' . $address[1] );
It uses the function to return a formatted string sprintf()
and the so-called. heredoc syntax for specifying a multi-line string.
An alternative option is to capture all output to a variable using output buffering: ob_start()
will enable writing the entire output to the buffer. After that, do the usual echo
and so on. Output "on the screen" of your fragment - but everything is still in the buffer. And from there you need to pull the content into a variable: ob_get_clean()
. But I would recommend simply collecting the string.