IF statement in a do_shortcode

Is it possible to do a if statement in a do_shortcode?

<?php 
    echo do_shortcode("[table width='500'] " . 
        if ( have_posts() ) : 
            while ( have_posts() ) : 
                the_post(); 
                the_content(); 
            endwhile; 
        endif; . 
    "[/table]"); 
?>

It gives me an unexpected T_IF.

Read More

EDIT: And without the IF statement it gives the post outside the shortcode.

Related posts

1 comment

  1. No. echo do_shortcode() is a function call. You can not pass a conditional statement as an argument of a function. What you need to do is pass in the returned result of your query as an argument of the function;

    //assuming you have taken care of your query prior to this point
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    
        $content = get_the_content(); //store content in variable
    
        echo do_shortcode("[table width='500'] ". $content . "[/table]"); 
    
    endwhile; endif;
    

    Note:

    In the example above, to prevent your content being echoed immediately you must call get_the_content() which returns its value as opposed to the_content() which immediately echo’s the content. That is why your content appears outside of the shortcode when run without the incorrect conditional statement passed as an argument.

    Extended answer:

    In light of your additional comment and extended question, to check for the existence of some “thing” or that some “thing” meets a particular condition you would conduct your testing outside of the function call to your shortcode much in the same way as we have done above;

    //assuming you have taken care of your query prior to this point
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    
        $content = get_the_content(); //store content in variable
        
        $thing = get_post_meta( get_the_ID(), 'thing', true );
    
        if ($thing === "yes") {
           
           //assuming you want to concatenate your content with an image
           $content = $content . '<br> <img src="path_to_image" />';
    
        } 
    
        echo do_shortcode("[table width='500'] ". $content . "[/table]"); 
    
    endwhile; endif;
    

Comments are closed.