【问题标题】:Get an array of the number of post per year of a custom post type (Wordpress)获取自定义帖子类型(Wordpress)的每年帖子数量的数组
【发布时间】:2021-09-20 05:38:05
【问题描述】:

我有一个名为“论文”的自定义帖子类型,为了提供图表,我需要一个包含每年有帖子的帖子数量的数组。

我尝试过使用wp_count_posts(),但它只是给了我帖子类型的总数,而get_archives() 只是静态的,我需要使用特定信息,例如每年的帖子数量。

有人知道怎么做吗?希望你能帮助我。

【问题讨论】:

  • 为此使用 wp_count_posts() 函数。 developer.wordpress.org/reference/functions/wp_count_posts 。还有你所说的“帖子数量数组”是什么意思?
  • 嗨,wp_count_posts() 函数确实为我提供了自定义帖子类型的帖子数量,但我需要该 CPT 每年的帖子数量
  • 如果你想计算成本并且发布数据是数组格式,那么你应该试试这个: $posts = get_posts([ 'post_type' => 'your custom post type', 'post_status' => '全部', 'posts_per_page' => -1 ]);

标签: wordpress


【解决方案1】:

对于任何一直想知道同样事情的人,我从其他论坛得到它:

我创建了一个基本示例,说明如何实现此结果。

// get all posts from our CPT no matter the status
$posts = get_posts([
    'post_type'      => 'papers', // based on the post type from your qeustion
    'post_status'    => 'all',
    'posts_per_page' => -1
]);

// will contain all posts count by year
// every year will contain posts count by status (added as extra =])
$posts_per_year = [];

// start looping all our posts
foreach ($posts as $post) {
    // get the post created year
    $post_created_year = get_the_date('Y', $post);

    // check if year exists in our $posts_per_year
    // if it doesn't, add it
    if (!isset($posts_per_year[$post_created_year])) {
        // add the year, add the posts stauts with the initial amount 1 (count)
        $posts_per_year[$post_created_year] = [
            $post->post_status => 1
        ];
    // year already exists, "append" to that year the count
    } else {
        // check if stauts already exists in our year
        // if it exist, add + 1 to the count
        if (isset($posts_per_year[$post_created_year][$post->post_status])) {
            $posts_per_year[$post_created_year][$post->post_status] += 1;
        // it doesnt exist, add the post type to the year with the inital amount 1 (count)
        } else {
            $posts_per_year[$post_created_year][$post->post_status] = 1;
        }
    }
}

在这里获得完整的答案: https://wordpress.stackexchange.com/questions/395928/get-an-array-of-the-number-of-post-per-year-of-a-custom-post-type-wordpress/396047#396047

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

获取去年发布的帖子

$today = getdate();
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'date_query' => array(
        array(
            'year'  => $today['year'] - 1,
        ),
    ),
);
$result = new WP_Query($args);
$count = $result->found_posts;
echo $count;

其他不同的方式

$args = array(
    'type'              => 'yearly',
    'post_type'         => 'post',
    'show_post_count'   => true
);
wp_get_archives($args);

这将输出以下内容 2015 (5) 2014 (3) 2011(10)

【讨论】:

  • 嗨,谢谢你的回答,但这不是我要找的。我需要一个数组来计算我在自定义帖子类型中每年发布的帖子数量。
猜你喜欢
  • 1970-01-01
  • 2011-04-17
  • 2016-04-27
  • 2016-12-29
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
相关资源
最近更新 更多