Custom $wpdb query to retrieve posts with custom fields

I have the following SQL query

SELECT ID, post_title, meta_key, meta_value FROM {$wpdb -> posts}
LEFT JOIN {$wpdb -> postmeta}
ON {$wpdb -> postmeta}.post_id = {$wpdb -> posts}.ID
WHERE {$wpdb -> posts}.post_type = ‘corsi’
AND {$wpdb -> posts}.post_status = ‘publish’
AND {$wpdb -> postmeta}.meta_key LIKE ‘mkc-%’

that retrieves the following results, if associated with the get_results() method of $wpdb

array(6) {
[0]=>
array(4) {
[“ID”]=>
string(2) “57”
[“post_title”]=>
string(39) “AutoCad 2D con esercitazioni meccaniche”
[“meta_key”]=>
string(11) “mkc-geco_id”
[“meta_value”]=>
string(1) “1”
}
[1]=>
array(4) {
[“ID”]=>
string(2) “57”
[“post_title”]=>
string(39) “AutoCad 2D con esercitazioni meccaniche”
[“meta_key”]=>
string(13) “mkc-geco_code”
[“meta_value”]=>
string(7) “CS01A08”
}
[2]=>
array(4) {
[“ID”]=>
string(2) “57”
[“post_title”]=>
string(39) “AutoCad 2D con esercitazioni meccaniche”
[“meta_key”]=>
string(13) “mkc-programme”
[“meta_value”]=>
string(0) “”
}
[3]=>
array(4) {
[“ID”]=>
string(2) “58”
[“post_title”]=>
string(5) “Prova”
[“meta_key”]=>
string(11) “mkc-geco_id”
[“meta_value”]=>
string(0) “”
}
[4]=>
array(4) {
[“ID”]=>
string(2) “58”
[“post_title”]=>
string(5) “Prova”
[“meta_key”]=>
string(13) “mkc-geco_code”
[“meta_value”]=>
string(0) “”
}
[5]=>
array(4) {
[“ID”]=>
string(2) “58”
[“post_title”]=>
string(5) “Prova”
[“meta_key”]=>
string(13) “mkc-programme”
[“meta_value”]=>
string(0) “”
}
}

Is possible to edit the query, in order to achieve the following result?

array(2) {
[0]=>
array(5) {
[“ID”]=>
string(2) “57”
[“post_title”]=>
string(39) “AutoCad 2D con esercitazioni meccaniche”
[“mkc-geco_id”]=>
string(1) “1”
[“mkc-geco_code”]=>
string(7) “CS01A08”
[“mkc-programme”]=>
string(0) “”
}
[1]=>
array(2) {
[“ID”]=>
string(2) “58”
[“post_title”]=>
string(5) “Prova”
[“mkc-geco_id”]=>
string(0) “”
[“mkc-geco_code”]=>
string(0) “”
[“mkc-programme”]=>
string(0) “”
}
}

If was not possible via SQL how to do it via PHP?

Read more here:: Custom $wpdb query to retrieve posts with custom fields

Leave a Reply

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