是否在Author.php中按自定义帖子类型显示用户的帖子计数?

时间:2019-10-15 作者:Duy Hữu

我在“如何在管理员的用户列表中按自定义帖子类型显示用户帖子数量”链接中看到了代码,但我希望在作者中显示帖子数量。php

Showing User's Post Counts by Custom Post Type in the Admin's User List?

在用户中显示。类似php的图像:

enter image description here

但我希望显示的帖子和作者的图片一样重要。php,请帮帮我,谢谢。

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

在这里,我修改了您给出的URL中的代码。

function _yoursite_get_author_post_type_counts() {
    static $counts;
    if (!isset($counts)) {
        global $wpdb;
        global $wp_post_types;
        $sql = <<<SQL
        SELECT
        post_type,
        post_author,
        COUNT(*) AS post_count
        FROM
        {$wpdb->posts}
        WHERE 1=1
        AND post_type NOT IN (\'revision\',\'nav_menu_item\')
        AND post_status IN (\'publish\',\'pending\', \'draft\')
        GROUP BY
        post_type,
        post_author
SQL;
        $posts = $wpdb->get_results($sql);
        foreach($posts as $post) {
            $post_type_object = $wp_post_types[$post_type = $post->post_type];
            if (!empty($post_type_object->label))
                $label = $post_type_object->label;
            else if (!empty($post_type_object->labels->name))
                $label = $post_type_object->labels->name;
            else
                $label = ucfirst(str_replace(array(\'-\',\'_\'),\' \',$post_type));
            if (!isset($counts[$post_author = $post->post_author]))
                $counts[$post_author] = array();
            $counts[$post_author][] = array(
                \'label\' => $label,
                \'count\' => $post->post_count,
                \'type\' => $post->post_type,
                );
        }
    }
    return $counts;
}
$user_id = get_current_user_id();
$counts = _yoursite_get_author_post_type_counts();
$custom_column = array();
if (isset($counts[$user_id]) && is_array($counts[$user_id]))
    foreach($counts[$user_id] as $count) {
        // $link = admin_url() . "edit.php?post_type=" . $count[\'type\']. "&author=".$user_id;
        // admin_url() . "edit.php?author=" . $user->ID;
        // $custom_column[] = "\\t<tr><th><a href={$link}>{$count[\'label\']}</a></th><td>{$count[\'count\']}</td></tr>";
        echo $count[\'label\']. "  ".$count[\'count\']."<br />"; 
    }
}
我还没有测试,但它基于给定URL的代码。我刚刚回显了它,以验证是否显示了正确的数据。此外,您可以根据您的实际需求执行所需操作。

SO网友:Anteraez

您可以使用以下代码获取作者中用户发布的帖子数量。php文件

$author_id = get_queried_object_id();

$getAuthorPosts = new WP_Query(
    array(
        "post_type"      => "post", // Replace "post" with your custom post type. e.g. "book" OR "WHATEVER"
        "author"         => $author_id,
    )
);

echo $getAuthorPosts->found_posts; // Number of posts published by the author.