Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created May 6, 2015 09:15
Show Gist options
  • Save hellofromtonya/8ebc4173dc29dce01575 to your computer and use it in GitHub Desktop.
Save hellofromtonya/8ebc4173dc29dce01575 to your computer and use it in GitHub Desktop.
WordPress Developers Club Challenge - What is the SQL to get the count of all post meta where post ID = 1?
/**
* Get the number of meta for a specific Post ID
*
* @since 1.0.0
*
* @param integer $post_id Post ID to query for
* @return integer Returns the count number
*/
function tonya_get_meta_count_for_post_id( $post_id ) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare(
"
SELECT COUNT(*)
FROM {$wpdb->postmeta}
WHERE post_id = %d
",
$post_id
) );
}
/**
* Get the count for a specific Post ID and meta key
* Another version of the above function (food for thought)
*
* @since 1.0.0
*
* @param integer $post_id Post ID to query for
* @param string $meta_key Meta Key to query for
* @return integer Returns the count number
*/
function tonya_get_count_for_post_id_and_meta_key( $post_id, $meta_key ) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare(
"
SELECT COUNT(*)
FROM {$wpdb->postmeta}
WHERE post_id = %d AND meta_key = %s
",
$post_id, $meta_key
) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment