Skip to content

Instantly share code, notes, and snippets.

@nciske
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nciske/01748eb103dc781dfc2b to your computer and use it in GitHub Desktop.
Save nciske/01748eb103dc781dfc2b to your computer and use it in GitHub Desktop.
Count post meta by post_id
<?php
function wpdc_count_post_meta( $post_id ){
global $wpdb;
$sql = $wpdb->prepare( 'SELECT COUNT( meta_id ) FROM '.$wpdb->postmeta.' WHERE `post_id` = %d', $post_id );
$post_meta_count = $wpdb->get_var( $sql );
return $post_meta_count;
}
@hellofromtonya
Copy link

A couple of things for you:

  1. For the FROM, just do {$wpdb->postmeta} as this is already a property the WPDB class.
  2. What about if that post_id does not exist? What are you wanting to return from this function?
  3. If you opt to just return from get_var, then there is no need to assign it to a variable first before returning.

@nciske
Copy link
Author

nciske commented May 5, 2015

  1. Good point. I wasn't aware there were properties for core tables. Makes sense.
    I'm not a fan of the {var} style and prefer to make concatenation clearer.
  2. It would return 0 from MySQL. Could I return a WP_Error or false? Sure, but 0 is also true ;-)
  3. Yeah, that'd be shorter but assigning it to a variable makes the code read easier (what are we expecting back -- var makes that clearer) and makes debugging easier.

@hellofromtonya
Copy link

  1. Concatenation works too.
  2. Since we are doing COUNT() it will return 0 if the post_id does not exist. Other SQL queries using get_var() would return NULL if nothing was found. I just wanted you to think about it a bit. Good job.
  3. For optimization, assigning to a variable when that variable is not be reused does take up memory and CPU execution time, albeit small. I just wanted you to think about the efficiency side of coding.

Excellent job! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment