Count number of published posts by type

I have this code, but it shows the total number of posts published by post type ‘code’.

<?php
$count_posts = wp_count_posts('code')->publish;
echo $count_posts;
?>

I have 2 post types: ‘code’ and ‘shop’.
Post type code is “a child” for post type ‘shop’.
Therefore I need to show the post count for the “child” post type ‘code’ for those attached to the “parrent” post type ‘shop’.

UPDATE – SOLUTION (if any others are facing same problem) :

<?php
                            $result = $wpdb->get_results(
                                $wpdb->prepare(
                                    "SELECT COUNT(*) AS code_num FROM {$wpdb->prefix}postmeta AS postmeta LEFT JOIN {$wpdb->prefix}postmeta AS postmeta1 ON postmeta.post_id = postmeta1.post_id WHERE postmeta1.meta_key = 'code_expire' AND postmeta1.meta_value > %d AND postmeta.meta_key = 'code_shop_id' AND postmeta.meta_value = %s",
                                    current_time('timestamp'),
                                    $post->ID
                                )
                            );
                            $result = array_shift( $result );
                            echo '
                                <li class="list-group-item">
                                    <span class="badge">'.$result->code_num.'</span>
                                    <a href="'.esc_url( get_permalink( $post->ID ) ).'"> '.$post->post_title.' </a>
                                </li>';
    ?>

Big thanks to Ahmed!

2 Answers
2

If you prefer the $wpdb direct queries you can use something like this:

global $wpdb;   
$count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type="code" and post_status="publish"" );
echo $count;

In the sql query above change the post_type to whatever you like. This will return count of published posts under specific post type only.

If you want to query counts from multiple post types do this query:

global $wpdb;   
$count = $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type IN ( 'code', 'shop', 'post', 'etc' ) and post_status="publish"" );
echo $count;

Hope that helps.

Leave a Comment