获取自定义帖子类型(WordPress)每年的帖子数组

时间:2021-09-21 作者:Daniel Leandro

我有一个自定义的帖子类型,叫做;论文“;,而且,为了提供一个图表,我需要一个每年有帖子的帖子数量数组。

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

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

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

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

// 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;
        }
    }
}

// this is for debugging, to see what our variable contains
// after the loop
echo \'<pre>\';
print_r($posts_per_year);
echo \'</pre>\';
在我运行此代码的站点中,这是我的结果,使用print_r

Array
(
    [2021] => Array
        (
            [publish] => 28
            [pending] => 1
            [draft] => 1
            [private] => 1
        )

    [2020] => Array
        (
            [trash] => 2
        )
)
我不知道你想如何输出这个,但现在你有了一个起点,最终数组的视觉表示,$posts_per_year, 所以你可以随心所欲。

相关推荐

Get full image array

当我使用高级自定义字段时,我可以返回上载的完整图像数组。是否有本机WordPress方法可以通过图像ID获取媒体库中任何图像的完整图像阵列?我可以找到方法来获取alt文本和特定的图像大小,但不能获取数组本身。。。