0

Here is the code that I use to counts posts for one post_type, I would like to use multiple post_type ( post_type_1, post_type_2... ) anyone can help me doing this ?

Thanks for the help.

<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>

<h2>Post Count: <?php echo $post_count; ?></h2>
1

OK, so there are some problems with your code...

  1. Your SQL isn't very safe. It would be much nicer, if you used prepare method:

    $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_author = %d AND post_type = %s AND post_status = %s",
            $curauth->ID, 'post', 'publish'
        )
    );
    
  2. You clearly say, that you want to count only posts post_type = 'post' is the part that is responsible for that. So just remove that part or modify it according to your needs.

  3. Be careful counting different post types - remember that attachment (and so on) is also a post type.

  4. Use built in functions. It would be much nicer to use count_user_posts.

    <?php $curauth = $wp_query->get_queried_object(); ?>
    <h2>Post Count: <?php echo count_user_posts( $curauth->ID, 'post_type' ); ?></h2>
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.