skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    For anyone who has been wondering the same thing, I got it from other forum:

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

    Get the complete answer here: https://wordpress.stackexchange.com/questions/395928/get-an-array-of-the-number-of-post-per-year-of-a-custom-post-type-wordpress/396047#396047


  2. To get posts published from last year

    $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;
    

    Other different ways

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

    This will output the following
    2015 (5)
    2014 (3)
    2011 (10)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search