显示来自自定义Metabox选择的帖子计数

时间:2014-06-26 作者:user3756781

I was wondering if this is possible.

我有一个自定义的post类型调用项目,它显示一个带有下拉菜单的metabox。在这个下拉菜单中,我列出了几个选项:草稿、打开、挂起和完成。一旦您选择了您想要的字段,我希望只有在所选作者登录时,才能够在前端显示该选项的帖子计数。

例如,作者A在4篇不同的帖子上选择完成4次。因此,当作者A登录到该站点时,他会在前端看到一个数字4,并填写了单词。

这是我用来显示下拉菜单的内容

 array(
            \'name\'    => __( \'Project Status\', \'projects\' ),
            \'desc\'    => __( \'\', \'projects\' ),
            \'id\'      => $prefix . \'project_select\',
            \'type\'    => \'select\',
            \'options\' => array(
                \'Select a Status\' => __( \'Select a Status\', \'projects\' ),
                \'Draft\' => __( \'Draft\', \'projects\' ),
                \'Open\'   => __( \'Open\', \'projects\' ),
                \'Pending\'     => __( \'Pending\', \'projects\' ),
                \'Closed\'     => __( \'Closed\', \'projects\' ),
                \'Completed\'     => __( \'Completed\', \'projects\' ),
            ),

1 个回复
最合适的回答,由SO网友:Adam Mo. 整理而成

请尝试以下代码:

function postsCount($meta_value) {
    $args = array(
        \'numberposts\'   => -1,
        \'post_type\'        => \'custom_post_type\', // set you custom post type
        \'meta_key\'         => \'project_select\',
        \'meta_value\'       => $meta_value,
    );

    $my_posts = get_posts( $args ); 
    $postsCount = count($my_posts);
    return $postsCount;
}
if ( is_user_logged_in() ) {
    echo postsCount(\'Draft\');
    echo postsCount(\'Completed\');
}
或者,如果您想通过较少的代码获得所有计数,请尝试以下操作:

function postsCount() {
    if ( !is_user_logged_in() ) {
        return;
    }
    $meta_value_array = array( \'Draft\', \'Open\', \'Pending\', \'Closed\', \'Completed\');
    $postsCount = \'<ul>\';
    foreach ($meta_value_array as $meta_value) {
        $args = array(
            \'numberposts\'   => -1,
            \'post_type\'        => \'custom_post_type\', // set you custom post type
            \'meta_key\'         => \'project_select\',
            \'meta_value\'       => $meta_value,
        );

        $my_posts = get_posts( $args ); 
        $postsCount = count($my_posts);
        $postsCount .= \'<li>\' .$meta_value. \' \' .$postsCount. \'</li>\';
    }
    $postsCount .= \'</ul>\';
    return $postsCount;
}

echo postsCount();

结束

相关推荐

Display Custom Posts

我已经创建了名为“review”的自定义帖子。从WP管理员我可以创建这些自定义帖子。但要在用户端显示它们,我面临一个问题。在开发插件时,我不想在主题中创建模板。这是我用来显示自定义帖子的代码。但它显示的是404模板。function review_template_function($template_path){ global $post; if(get_query_var(\'post_type\') == \'review\'){ if(is_single()){&#