Home > Enterprise >  <p> is not in the result inside a PHP condition
<p> is not in the result inside a PHP condition

Time:07-02

what is the wrong in this code that makes the removed from the result

<?php if(the_field('price',$postID)) : ?>  
          <p > <?php the_field('price',$postID) ; ?></p> 
          <?php endif; ?> 

The result show only the price without the p element

enter image description here

CodePudding user response:

Using the_field() echos and get_field() returns the value of a specific field. So with your provided code if you change both to get_field() then it will display empty <p> tags as you're not echoing them.

The solution will be to change the if condition to get_field() and the one inside <p> tags would remain the_field().

<?php if (get_field('price', $postID)) : ?>  
  <p ><?php the_field('price', $postID); ?></p> 
<?php endif; ?> 

If you ever echo any tags then get_field() should be used.

if (get_field('price', $postID)) {  
  echo "<p class=\"price\">" . get_field('price', $postID) . "</p>";
}

Any function that echos its value should not be used inside if statement's (condition).

CodePudding user response:

Just change

the_field('price',$postID)

By

get_field('price',$postID)

And Enjoy!

CodePudding user response:

Your the_field() function echo the output, not returning the value as
@KIKOSoftware speculated. If it wouldn't echo and returned value instead, you'd end up with an empty <p> tag anyway, because there is no echo to output the result in your code.

If the_field() returned value, you'd need use either

<?php echo the_field('price',$postID) ; ?>

or

<?=the_field('price',$postID) ; ?>

So the answer is: check your the_field() function.

  • Related