Pete Norris
Pete Norris

Reputation: 1054

syntax for advanced custom fields in wordpress

I am trying to display a field, but it shows the value fine, but OUTSIDE of the tags?!??!

echo '<h2>'. the_field('where') .'</h2>';

Output =

"London"
<h2></h2>

Should be =

<h2>London</h2>

Upvotes: 0

Views: 115

Answers (2)

Vlad Preda
Vlad Preda

Reputation: 9920

Use this:

<h2><?php the_field('where'); ?></h2>

Explanation:

You code has the output it has because of how echo works. It first generates the whole string (running the functions), and then it renders the output. So, if the function the_field has output, it will generate what you see.

Basically your code is equivalent to:

$title = '<h3>'. the_field('where') .'</h3>';
echo $title;

Example:

function test() {
    echo '1';
    return '2';
}
echo 'PRE - ' . test() . ' - POST';

And here is the result:

$ php test.php
1PRE - 2 - POST

Upvotes: 0

user1646111
user1646111

Reputation:

Because you have a function like this:

function  the_field($text){
 echo $text;
}
echo '<h3>'. the_field('where') .'</h3>';

Change your function to:

function  the_field($text){
 return $text;
}
echo '<h3>'. the_field('where') .'</h3>';

Why? Because PHP executes the function before printing output of the echo.

Upvotes: 4

Related Questions