Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Im looking to count how many meta keys exist within a post, because each time a specific user action happens, a new meta key is created with a date in it.

I have this, which does not return anything (I'm looking for a number)...

$post_title = $row->post_title;
        $id = $row->ID;

$post_count = $wpdb->get_var("
                SELECT COUNT(DISTINCT $wpdb->postmeta.meta_key) FROM $wpdb->posts
                LEFT JOIN $wpdb->postmeta 
                WHERE $wpdb->posts.post_type = 'things'
                AND $wpdb->postmeta.meta_key = 'dates' 
                AND post_id = $id

        echo $post_title . ' (' . $post_count . ')' . "\n";

Similarly, I'd like to count the number of meta keys in total related to a custom post, any help on either of these would be greatly appreciated!

share|improve this question

1 Answer 1

I solved this problem with some more trial and error:

This got me the # of post meta with the correct id,

        $post_title = $row->post_title;
        $id = $row->ID;

$post_count = $wpdb->get_var("
                SELECT COUNT(*) FROM $wpdb->postmeta
                WHERE post_id = $id
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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