在“概览”仪表板小部件上仅显示当前作者的自定义帖子类型计数

时间:2018-11-09 作者:quantum_leap

我使用此代码在“概览”仪表板小部件上显示所有自定义帖子类型及其计数:

add_action( \'dashboard_glance_items\', \'cpad_at_glance_content_table_end\' );
function cpad_at_glance_content_table_end() {
$args = array(
    \'public\' => true,
    \'_builtin\' => false,
);
$output = \'object\';
$operator = \'and\';

$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types as $post_type ) {
    $num_posts = wp_count_posts( $post_type->name );
    $num = number_format_i18n( $num_posts->publish );
    $text = _n( $post_type->labels->singular_name, $post_type->labels->name, intval( $num_posts->publish ) );
    if ( current_user_can( \'edit_posts\' ) ) {
        $output = \'<a href="edit.php?post_type=\' . $post_type->name . \'">\' . $num . \' \' . $text . \'</a>\';
        echo \'<li class="post-count \' . $post_type->name . \'-count">\' . $output . \'</li>\';
        } else {
        $output = \'<span>\' . $num . \' \' . $text . \'</span>\';
            echo \'<li class="post-count \' . $post_type->name . \'-count">\' . $output . \'</li>\';
        }
    }
}
有没有办法只显示属于当前登录作者的帖子数量?

2 个回复
最合适的回答,由SO网友:rudtek 整理而成

我想你想要的是:

   // The user is logged, retrieve the user id (this needs to go above your foreach)
    $user_ID = get_current_user_id(); 
   // Now we have got the user\'s id, we can pass it to the foreach of your function(this needs to go into your foreach:  
    echo \'<li>Number of \'.$post_type->name.\' posts published by me: \' . count_user_posts( $user_ID , $post_type->name ).\'</li>\';

SO网友:quantum_leap

我已经修改了@rudtek的答案,我正在这里显示代码。基本上count_user_posts 所需功能name 方法传递给post类型,否则,输出为“0”。

add_action( \'dashboard_glance_items\', \'cpad_at_glance_content_table_end\' );
function cpad_at_glance_content_table_end() {
$args = array(
    \'public\' => true,
    \'_builtin\' => false,
);
$output = \'object\';
$operator = \'and\';

$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types as $post_type ) {
    $user_ID = get_current_user_id();
    $num_posts = count_user_posts( $user_ID , $post_type->name );
    $text = _n( $post_type->labels->singular_name, $post_type->labels->name, intval( $num_posts->publish ) );
    if ( current_user_can( \'edit_posts\' ) ) {

        $output = \'<a href="edit.php?post_type=\' . $post_type->name . \'">\' . $num_posts . \' \' . $text . \'</a>\';
        echo \'<li class="post-count \' . $post_type->name . \'-count">\' . $output . \'</li>\';
        } else {
        $output = \'<span>\' . $num_posts . \' \' . $text . \'</span>\';
            echo \'<li class="post-count \' . $post_type->name . \'-count">\' . $output . \'</li>\';
        }
    }
}

结束

相关推荐

Create small dashboard widget

我一直在尝试在admin中的一个用户的帐户页面中添加一列移动电话号码字段。所以我从https://coderwall.com/p/g72jfg/adding-a-phone-numer-field-to-wordpress-user-profile现在我要做的是,为仪表板构建一个自定义小部件,这样用户也可以直接从那里更改他的手机号码(因此小部件中还必须有一个更新按钮)。你可以看到为这个想法附上的照片-第一幅图是小部件在dashboad中的外观,-第二张图片是您现在可以在用户帐户中看到的。我知道一些使用ec