Return Number of published posts in a custom post type

<?php
    $counter=1;
    $counter_new=0;
    $args = array('posts_per_page' =>-1,'orderby' => 'post_date','order' =>'DESC','post_type' => 'interview','post_status' => 'publish',            
    'suppress_filters' => true );query_posts( $args );while (have_posts($args)) : the_post();
    if($counter < 8)
    {
        $counter++;
    }
    else
    {
        $counter_new++;
        $counter=1;
    }
endwhile;
?>  

I saw someone else code to find the number of post, as record increase it is not efficient. What is the right way to do? It looks stupid now.

Related posts

Leave a Reply

3 comments

  1. In case you use WPML wp_count_post() will not show correct count of posts for given language. Use this instead:

    $posts = get_posts('post_type=yourcustomposttype&suppress_filters=0&posts_per_page=-1');
    $count = count($posts); 
    echo $count;
    
  2. Take a look at the wp_count_posts() function.

    For your example:

    $count_posts = wp_count_posts('interview');
    $published_posts = $count_posts->publish;
    

    $published_posts will return the number of published posts in your ‘interview’ custom post type.

  3. One of the other answers won’t work if you have WMPL and translations. The other one will work, but will be very inefficient.

    With WPML, try this instead:

    function my_count_posts( string $post_type = 'post', string $language_code = '', string $post_status = 'publish' ): int {
        global $wpdb;
    
    
        $default_language_code = apply_filters( 'wpml_default_language', null );
        $language_code         = $language_code !== '' ? $language_code : $default_language_code;
        $translation_param     = $default_language_code == $language_code ? "IS NULL" : "= '{$default_language_code}'";
    
        $query = <<<SQL
                    SELECT COUNT( {$wpdb->prefix}posts.ID )
                    FROM {$wpdb->prefix}posts
                        LEFT JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id
                    WHERE {$wpdb->prefix}icl_translations.language_code = '{$language_code}'
                      AND {$wpdb->prefix}icl_translations.source_language_code $translation_param
                      AND {$wpdb->prefix}icl_translations.element_type = 'post_{$post_type}'
                      AND {$wpdb->prefix}posts.post_status = '$post_status'
                    SQL;
    
        return $wpdb->get_var( $query );
    }
    

    You’d use it like this:

    // counts published "posts" in the default language
    $count = my_count_posts();
    
    // counts posts of `post_type=custom_post_type` in the current language
    $count = my_count_posts('custom_post_type', apply_filters( 'wpml_current_language', '' ));