短语if语句

时间:2017-11-06 22:03:17

标签: php wordpress

我需要在帖子数为0时打印另一个短代码 我添加到此代码的任何代码都会返回致命错误

add_shortcode('reviews_total', 'reviews_total_func');

function reviews_total_func()
{ 

    global $post;
    $args = array(
                 'posts_per_page'   => -1,
                 'post_type' => 'testimonial',
                 'meta_key' => '_wpcf_belongs_' . $post->post_type . '_id', 
                'meta_value' => $post->ID,
    );

    $child_posts = get_posts($args);
    return count($child_posts);
}

如果count($ child_posts)= 0

,我需要查看另一个短代码

2 个答案:

答案 0 :(得分:0)

假设这个短代码的唯一目的是输出帖子的数量,为什么不在返回值之前检查它?

示例:

add_shortcode('reviews_total', 'reviews_total_func');

function reviews_total_func()
{ 

    global $post;
    $args = array(
                 'posts_per_page'   => -1,
                 'post_type' => 'testimonial',
                 'meta_key' => '_wpcf_belongs_' . $post->post_type . '_id', 
                'meta_value' => $post->ID,
    );

    $child_posts = get_posts($args);

    if(count($child_posts) > 0)
         return count($child_posts);
    else
         return "Your custom, alternate zero-posts text";
}

答案 1 :(得分:0)

使用函数do_shortcode

执行另一个短代码
add_shortcode('reviews_total', 'reviews_total_func');

function reviews_total_func() { 
    global $post;
    $args = array(
                 'posts_per_page'   => -1,
                 'post_type' => 'testimonial',
                 'meta_key' => '_wpcf_belongs_' . $post->post_type . '_id', 
                'meta_value' => $post->ID,
    );

    $child_posts = get_posts($args);

    if(count($child_posts) > 0)
        return count($child_posts);

    return do_shortcode( '[my-short-code]' );
}