Category Archives: MySQL

Query Multiple Meta Values in WordPress and use CONCAT()

I needed to pull two specific meta values for each custom post type into an array. I wanted them to be combined as one reference, and I wanted to use only one query.

With the help of multiple online sources, I was able to figure it out.
function get_your_meta($key1 = '', $key2 = '', $type = 'post', $status = 'publish') {
    global $wpdb;
    if(empty($key1) || (empty($key2))) {
    $r = $wpdb->get_results( $wpdb->prepare(
			CONCAT(pm.meta_value, ' ', pm2.meta_value) AS `name`,
		FROM {$wpdb->posts} p
		INNER JOIN {$wpdb->postmeta} pm
			ON p.ID = pm.post_id
        INNER JOIN {$wpdb->postmeta} pm2
			ON p.ID = pm2.post_id
		WHERE pm.meta_key = '%s'
		AND pm2.meta_key = '%s'
        AND p.post_status = '%s' 
        AND p.post_type = '%s'
    $key1, $key2, $status, $type) );
    return $r;
Simply call the function using
$arr = get_your_meta("meta_key_1", "meta_key_2", "post"); 
Of course, if you’re using a custom post type, change as such.