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))) {
		return;
	}
    $r = $wpdb->get_results( $wpdb->prepare(
    "
        SELECT
			CONCAT(pm.meta_value, ' ', pm2.meta_value) AS `name`,
			pm.post_id
		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.

Cheers

1 thought on “Query Multiple Meta Values in WordPress and use CONCAT()

  1. Jaxon Hopkins

    Hey Admin,
    This question may be a little off-topic, the beneath code is the code that i established to delete a history from the database but it is not working.
    it connects adequately to the table in the database but it is not deleting the record. Please some one assist me.

    code for building desk test_mysql in examination db

    Build Desk `test_mysql` (
    `id` int(4) NOT NULL vehicle_increment,
    `name` varchar(sixty five) NOT NULL default ”,
    `lastname` varchar(sixty five) NOT NULL default ”,
    `email` varchar(sixty five) NOT NULL default ”,
    Main Essential (`id`)
    ) Variety=MyISAM Vehicle_INCREMENT=seven


    — Dumping information for table `test_mysql`

    INSERT INTO `test_mysql` VALUES (1, ‘Billly’, ‘Blueton’, ‘bb5@phpeasystep.com’)
    INSERT INTO `test_mysql` VALUES (2, ‘Jame’, ‘Campbell’, ‘jame@someplace.com’)
    INSERT INTO `test_mysql` VALUES (3, ‘Mark’, ‘Jackson’, ‘mark@phpeasystep.com’)
    INSERT INTO `test_mysql` VALUES (4, ‘Linda’, ‘Travor’, ‘lin65@phpeasystep.com’)
    INSERT INTO `test_mysql` VALUES (5, ‘Joey’, ‘Ford’, ‘fordloi@somewhere.com’)
    INSERT INTO `test_mysql` VALUES (6, ‘Sidney’, ‘Gibson’, ‘gibson@phpeasystep.com’)

    php code to delete document type the DB is saved as file title examination_mysqland the code i utilised is
    Nice One!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *