Last active
May 3, 2018 16:14
-
-
Save shramee/3c4ec75e93a5b9b23ba2da33718b6436 to your computer and use it in GitHub Desktop.
Query user meta for a user
This file contains hidden or 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 | |
/** | |
* Query user meta | |
* | |
* @param string|array $name_patt Meta key pattern match | |
* @param int $uid User ID | |
* @param string $query_suffix SQL query suffix | |
* | |
* @return array|null Results of query | |
*/ | |
function shramee_query_user_meta( $name_patt, $uid = 0, $query_suffix = 'ORDER BY umeta_id DESC;' ) { | |
if ( ! $uid ) { | |
$uid = get_current_user_id(); | |
} | |
if ( $uid ) { | |
/** @var wpdb $wpdb */ | |
global $wpdb; | |
$select = '`meta_key` as `key`, `meta_value` as `value`'; | |
// Escape for sql query | |
$name_patt = esc_sql( $name_patt ); | |
if ( is_array( $name_patt ) ) { | |
$name_patt = implode( "' OR `meta_key` LIKE '", $name_patt ); | |
} | |
return $wpdb->get_results( | |
"SELECT {$select} FROM {$wpdb->usermeta} " . | |
"WHERE ( `meta_key` LIKE '{$name_patt}' ) AND `user_id` = {$uid} " . | |
$query_suffix | |
); | |
} | |
return []; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment