Skip to content

Instantly share code, notes, and snippets.

@robhadfield
Created February 4, 2016 17:09
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 robhadfield/840ec72b0d1f89b828fa to your computer and use it in GitHub Desktop.
Save robhadfield/840ec72b0d1f89b828fa to your computer and use it in GitHub Desktop.
WP SQL for pulling meta_data as "Key" -> "Value" pairs
// 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