Last active
January 19, 2022 23:53
-
-
Save ahmu83/76496f1d9637837ecb07e8ec801ec9fd to your computer and use it in GitHub Desktop.
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 | |
/** | |
* This function retrieves post meta using a custom $wpdb query. There are two reasons for this approach. | |
* 1. When doing get_post_meta to query all the meta keys it returns an array or array | |
* 2. This function also queries for LIKE fields. i.e, get_post_meta2(1, 'first_name, last_name, hobby_%') | |
* | |
* TODO: distinct meta_key, meta_value | |
* | |
*/ | |
/** | |
* Retrieves post meta field(s) for the given post ID. | |
* | |
* @param int $id Post ID | |
* @param boolean|string|array $keys array or a comma separated meta_key string | |
* @return array | |
*/ | |
function get_post_meta2($id, $keys = false) { | |
global $wpdb; | |
if ( $keys && is_string($keys) ) { | |
$keys = array_map(function($n) { | |
return trim($n); | |
}, explode(',', $keys)); | |
} | |
$fields = "meta_key 'key', meta_value 'val'"; | |
$query = "SELECT {$fields} FROM {$wpdb->postmeta} WHERE post_id = {$id}"; | |
if ( is_array($keys) ) { | |
$query .= " AND ("; | |
foreach ($keys as $k => $key) { | |
$first_char = substr($key, 0, 1); | |
$last_char = substr($key, -1); | |
if ($first_char == '%' || $last_char == '%') { | |
$operator = 'LIKE'; | |
} else { | |
$operator = '='; | |
} | |
$query .= "meta_key " . $operator . " '" . $key . "'"; | |
if ( $k == count($keys) - 1 ) { | |
$query .= ")"; | |
} else { | |
$query .= " OR "; | |
} | |
} | |
} | |
$query .= " ORDER BY meta_id DESC"; | |
$results = $wpdb->get_results($query, ARRAY_A); | |
$rows = array(); | |
foreach ($results as $result) { | |
$rows[$result['key']] = $result['val']; | |
} | |
return $rows; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment