2

I have an $array that prints out to be as follows.

Array ( [post-12] => 12 [post-160] => 160 )

What WordPress function could I use to check how many of the post ID's in the array belong to a specific category, say category with ID 45.

I tried doing the following.

$post_id_array = $array;
$category = '45';
$count = count(in_category( $category, $post_id_array ));
echo $count;

It doesn't work.

2
  • OK, can some mod transfer this question there?
    – Sam
    Dec 28, 2014 at 9:57
  • You can try to flag it for moderator attention with the explicit reason, but I'm not 100% sure they can do that. Or you can copy/paste and delete this one ;-)
    – TLama
    Dec 28, 2014 at 9:58

2 Answers 2

2

A much faster solution would be to query the database once instead of over and over for each post ex:

function count_posts_in_term($posts = array(),$term_taxonomy_id = 0){
    global $wpdb;
    $count = 0 ;
    $count = $wpdb->get_var(
        $wpdb->prepare("SELECT count(object_id) 
            FROM $wpdb->term_relationships 
            WHERE term_taxonomy_id = %s 
            AND object_id IN(".implode(',',$posts).")",
            $term_taxonomy_id
        )
    );
    return $count;
}

usage:

echo count_posts_in_term($array_of_posts,$cat_term_id);
1

I have successfully returned the counts using the following code. Just in case someone may later view this question.

$count = 0;
$category = '45';
foreach ( $array as $post_id ) {
    if (in_category( $category, $post_id )) {
        $count++;
    }
}
echo $count;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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