添加显示多个时间的短代码标题

时间:2015-09-16 10:09:56

标签: php wordpress wordpress-plugin

我的代码如下所示,在帖子中添加短代码。当我添加两次短代码时,它显示我标题两次,我在代码中添加“最近的帖子”是否有办法显示此标题只有顶部意味着一次?

/*shortcode start*/
add_shortcode( 'recent-posts', 'PL_recent_posts' );

function PL_recent_posts( $atts  ) {
extract( shortcode_atts( array(
    'numbers' => '5',
    'order' => 'ASC',

), $atts ) );

$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' , 'colorss' =>     $color ) );


if ( $rposts->have_posts() ) {
    $html = '<h3>Recent Posts</h3><ul class="recent-posts">';
    while( $rposts->have_posts() ) {
        $rposts->the_post();
        $html .= sprintf(
            '<li><a href="%s" title="%s">%s</a></li>',
            get_permalink($rposts->post->ID),
            get_the_title(),
            get_the_title()
        );
    }
    $html .= '</ul>';
}
wp_reset_query();

return $html;
}

Ecample Image

1 个答案:

答案 0 :(得分:1)

定义一个全局变量以检测是否已添加标题。

function PL_recent_posts( $atts ) { 
    global $title_added;
    ...
    if ( $rposts->have_posts() ) {
        if ( $title_added ) {
            $html = '<ul class="recent-posts">';
        } else {
            $html = '<h3>Recent Posts</h3><ul class="recent-posts">';
            $title_added = true;
        }

希望有帮助..!