Last active
May 3, 2018 16:12
-
-
Save shramee/127b8bd42008499a1b327d7f8b0f8419 to your computer and use it in GitHub Desktop.
WordPress - Query post/user meta
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 | |
/** | |
* Query user meta table | |
* | |
* @param string|array $name_patt Meta key pattern match | |
* @param string $query_suffix SQL query suffix | |
* @param bool $post_meta Whether to query post meta table | |
* | |
* @return array|null Results of query | |
*/ | |
function shramee_query_meta( $name_patt, $query_suffix = '', $post_meta = false ) { | |
/** @var wpdb $wpdb */ | |
global $wpdb; | |
$select = '`meta_key` as `key`, `meta_value` as `value`'; | |
if ( $post_meta ) { | |
$table = $wpdb->postmeta; | |
$select .= ', `post_id` as `id`'; | |
} else { | |
$table = $wpdb->usermeta; | |
$select .= ', `user_id` as `id`'; | |
} | |
$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 {$table} " . | |
"WHERE ( `meta_key` LIKE '{$name_patt}' ) " . | |
$query_suffix | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment