Skip to content

Instantly share code, notes, and snippets.

@shramee
Last active May 3, 2018 16:16
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 shramee/4e88c569379e54dad6a456a9db8f99cc to your computer and use it in GitHub Desktop.
Save shramee/4e88c569379e54dad6a456a9db8f99cc to your computer and use it in GitHub Desktop.
WordPress - Query user meta
<?php
/**
* Query user meta table
*
* @param string|array $name_patt Meta key pattern match
* @param string $query_suffix SQL query suffix
*
* @return array|null Results of query
*/
function shramee_query_user_meta_table( $name_patt, $query_suffix = '' ) {
/** @var wpdb $wpdb */
global $wpdb;
$select = '`meta_key` as `key`, `meta_value` as `value`, `user_id` as `id`';
// 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}' ) " .
$query_suffix
);
}
@shramee
Copy link
Author

shramee commented May 3, 2018

P.S. https://gist.github.com/shramee/127b8bd42008499a1b327d7f8b0f8419#file-query-meta-php to have single function for both post and user meta.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment