• Hi,

    OK, all you MySQL wizzards:
    I’d like to get the count of posts in a particular category that have a particular custom meta field. Ideally, I want just the count, I don’t need the actual post data, so I’m assuming it would be more efficient not to have that returned. I guess that means not using the builtin WordPress database API calls though…

    Any tips, anyone?

    Cheers,

    a|x

Viewing 7 replies - 1 through 7 (of 7 total)
  • <?php 
    
    $categories = get_categories( $args );
    $counter = 0;
    
    foreach($categories as $post){
       setup_postdata($post);
       $meta_query = get_post_meta($post->ID, 'name_of_meta_tag', true);
       if($meta_query){
          if($meta_query == "whatever"){
             $counter++;
          }
       }
    }
    
    echo $counter;
    ?>
    Thread Starter toneburst

    (@toneburst)

    Hi jimmyt1988,

    thanks very much for getting back to me. I’m no expert on how WordPress and MySQL works, but this seems intuitively to be massive overkill, in terms of data throughput, when I don’t need any of the post content at all- literally just the number of posts in each category with a particular meta field. Maybe this is the only way to do it though…

    a|x

    Moderator bcworkz

    (@bcworkz)

    You can directly query the database to get the count you want, the query will be rather complex because you need to do a few joins to access the table which holds category info.

    toneburst… sorry about that. I was flicking through posts and came up with the fastest solution i could think of. I can prepare a mysql join for u if i remember to tune back in tonight.

    Thread Starter toneburst

    (@toneburst)

    Hi jimmyt1988

    no problem. If you get a chance to prepare that MySQL statement, that would be very cool. I’m afraid my database query skills aren’t up to much.

    Thanks again,

    a|x

    SELECT COUNT(tr.object_id) FROM wp_term_relationships tr, wp_terms t, wp_term_taxonomy tt, wp_postmeta m WHERE t.term_id = tt.term_id AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'category' AND m.post_id = tr.object_id AND m.meta_value != '' AND m.meta_key = 'Your Custom Meta' AND t.name = 'Name of the Category'

    Thread Starter toneburst

    (@toneburst)

    Hi rcmck,

    wow… I’d never have worked that out! Thank you very much!!

    a|x

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Count Of Posts in Given Category With Specific Custom Meta’ is closed to new replies.