简体   繁体   English

PHP wordpress在短代码中执行功能

[英]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. 这是到目前为止我拥有的-我的php知识不是很好。 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 . 您的函数应返回值,而不是使用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() ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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