• Hi, I have the below code that counts posts from categories and then performs and echoes a sum. This is working fine except that it affect the posts that are displayed on the page. I guess this is because I’m using “query_posts”. Is there a way of getting just the post count without changing the posts on the page? I’ve tried changing “query_posts” to “count_posts”. But it didn’t work. Any help would be great.

    <?php
    //melbourne postive
    $posts = query_posts(array('category__and' => array(6,25)));
    $melbpos = count($posts);
    
    ?>
    
    <?php
    //melbourne negative
    $posts = query_posts(array('category__and' => array(10,25)));
    $melbneg = count($posts);
    
    ?>
    
    <div style="color:#0F6;"><img src="teamImages/Melbourne.png" width="48" height="31" alt="Melbourne" />Melbourne
    <?php echo ($melbpos - $melbneg); ?>
    
    </div>
Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter eckul

    (@eckul)

    Thanks, I tried but couldn’t get it to work. But it helped me find a solution. I’ve used the below code. I’m sure it’s not the right way to do it, but it’s working well. cheers

    $posts = query_posts( array( 'category__not_in' => array(  ) ) );
    $allpos = count($posts);

    There may be a better solution to it, this should give you definite result

    <?php
    $cat_ids = array(6,25);
    function count_posts_by_category($cat_ids){
            $count =0;
            $arg = array( 'posts_per_page' => -1, 'category__in'=>$cat_ids,  'post_status'=>'publish');
    	$the_query = new WP_Query( $arg);
    
        if ( $the_query->have_posts() ){
                while ( $the_query->have_posts() ) {
                        $the_query->the_post();
                        $count++;
        }}
        wp_reset_postdata();
    
        return $count;
    }
    
    $total_count = count_posts_by_category($cat_ids);
    ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Counting post and displaying result’ is closed to new replies.