Andrew Andrew - 18 days ago 4
PHP Question

Why does assigning a PHP function to a variable execute it?

I am using this in WordPress:

<?php if ( !is_front_page()) {

$title = the_title();

echo <<<EOT

<div class="featured-header col-xs-12 col-sm-12 col-md-12 col-lg-12 cf">
<span class="featured-title">$title</span>
</div>

EOT;
} ?>


However, the page title is generated by the PHP BEFORE the div. It looks like the declaration of the $title variable itself is executing the
the_title()
function.

Why is this?

EDIT:

Thanks for the explanation! Here is the working code now:

<?php if ( !is_front_page()) {

$title = get_the_title();
$thumbnail = get_the_post_thumbnail_url();

echo <<<EOT

<div class="featured-header col-xs-12 col-sm-12 col-md-12 col-lg-12 cf" style="background-image: url('$thumbnail');">
<span class="featured-title animated fadeIn">$title</span>
</div>
EOT;

} ?>

Answer

the_title() is a template function that display (echo) the title. If you want to store the title in a var, use get_the_title() instead.

Note that most of WP template functions work like this : get_the_content() vs the_content(), get_the_date() vs the_date()...

Comments