admin管理员组文章数量:1287489
I have a custom post type called "papers", and, to feed a chart, I need an array of the number of posts per year that have posts.
I've tried with wp_count_posts()
but it just give me the total number of post types, and get_archives()
is just to static, and I need to use specific information like the number of post per year.
Does anyone know how to do this? Hope you can help me.
I have a custom post type called "papers", and, to feed a chart, I need an array of the number of posts per year that have posts.
I've tried with wp_count_posts()
but it just give me the total number of post types, and get_archives()
is just to static, and I need to use specific information like the number of post per year.
Does anyone know how to do this? Hope you can help me.
Share Improve this question asked Sep 21, 2021 at 14:31 Daniel LeandroDaniel Leandro 175 bronze badges1 Answer
Reset to default 0I have created a basic example on how you could achieve this result.
// 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>';
In the site that I runed this code this was my result, using print_r
Array
(
[2021] => Array
(
[publish] => 28
[pending] => 1
[draft] => 1
[private] => 1
)
[2020] => Array
(
[trash] => 2
)
)
I have no idea how you want to output this but now you have a starting point with a visual representation of the final array, $posts_per_year
, so you can do with it what ever you want.
本文标签: Get an array of the number of post per year of a custom post type (Wordpress)
版权声明:本文标题:Get an array of the number of post per year of a custom post type (Wordpress) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741304444a2371283.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论