little with mySQL wp db query.
-
Hi,
I’m trying to adapt this function to return not just the value of each custom field but also the $post_id associated with it in an array; they are both in the same table ($wpdb->postmeta) but im not very knowledgeable in mySQL…
I realize get_col will only retrieve one column so it is not as simple as adding an ‘AND pm.post_id’ to the SELECT
summarizing, what i need is a function which retrieves all values in a custom field and their associated post id.
Any help is appreciated.
if ( ! function_exists( 'get_meta_values' ) ) { function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) { global $wpdb; if( empty( $key ) ) return; $r = $wpdb->get_col( $wpdb->prepare( " SELECT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND p.post_status = '%s' AND p.post_type = '%s' ", $key, $status, $type ) ); return $r; } }
Thanks to t31os on
https://wordpress.stackexchange.com/questions/9394/getting-all-values-for-a-custom-field-key-cross-post for the function in the first place.Thanks
- The topic ‘little with mySQL wp db query.’ is closed to new replies.