Created
February 4, 2016 17:09
-
-
Save robhadfield/840ec72b0d1f89b828fa to your computer and use it in GitHub Desktop.
WP SQL for pulling meta_data as "Key" -> "Value" pairs
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
// Example ID | |
$id = '1'; | |
// DB connection and query | |
global $wpdb; | |
$rows = $wpdb->get_results( | |
" | |
SELECT $wpdb->postmeta.meta_key, $wpdb->postmeta.meta_value | |
FROM $wpdb->postmeta | |
WHERE | |
$wpdb->postmeta.post_id = 1361 | |
GROUP BY | |
$wpdb->postmeta.meta_key | |
" | |
); | |
// Create array | |
$fields = []; | |
// Loop through to sort into pairs | |
foreach($rows as $r) { | |
$k = $r->meta_key; | |
$v = $r->meta_value; | |
$fields[$k] = $v; | |
} | |
// Array is now one dimensional so can the values can be accessed by the key | |
var_dump($fields['meta_key_name']); | |
// Output 'meta_key_value' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment