Last active
August 29, 2015 14:20
-
-
Save nciske/01748eb103dc781dfc2b to your computer and use it in GitHub Desktop.
Count post meta by post_id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
- 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. - It would return 0 from MySQL. Could I return a WP_Error or false? Sure, but 0 is also true ;-)
- 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.
- Concatenation works too.
- 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.
- 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
A couple of things for you: