简体   繁体   中英

PHP wordpress excecute a function within a shortcode

I have created a function that gathers all the images from a set of posts. I'm trying to add those images between an opening and closing shortcode that creates a slider.

Here is what I have so far - my php knowledge isn't great. Can anyone point out why this might not be working. Thanks

<?php 
function pplSlider()
{
$my_query = new WP_Query( "category_name=editorial&posts_per_page=-1" ); 

if ( $my_query->have_posts() ) : 

while ( $my_query->have_posts() ) : 
    $my_query->the_post();
    the_post_thumbnail(array(300,300));

    if (($my_query->current_post +1 )< $my_query->post_count)
        echo '/!';

endwhile; 
endif;
}
}
echo do_shortcode('[wpic]' . pplSlider() . '[/wpic]');

?>

Your function should return the value, instead of using echo .

One way around it is to return the output buffering, like this:

function pplSlider(){
    ob_start();
    $my_query = new WP_Query( "category_name=editorial&posts_per_page=-1" ); 
    if ( $my_query->have_posts() ) : 
        while ( $my_query->have_posts() ) : $my_query->the_post();
            the_post_thumbnail(array(300,300));
            if (($my_query->current_post +1 )< $my_query->post_count)
                echo '/!';

        endwhile; 
    endif;
    return ob_get_contents();
}

echo do_shortcode( sprintf( '[wpic]%s[/wpic]', pplSlider() ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM