So I’m trying to integrate a bit of WordPress with a backend. Their MySQL schema isn’t too great, especially when you add in Woocommerce.
I’ve come up with the following query:
SELECT wp.*
FROM wp_postmeta wp
INNER JOIN (SELECT post_id
FROM wp_postmeta
WHERE ( `meta_key` = '_shipping_method'
AND `meta_value` = 'free_shipping' )
OR ( `meta_key` = '_order_items'
AND `meta_value` LIKE '%search%' )) a
ON a.post_id = wp.post_id
ORDER BY wp.post_id DESC
To be run on this table https://i.stack.imgur.com/qMHQp.jpg to select the right things for certain people.
Now when I var_dump this in PHP it comes out like so (truncated) – http://pastebin.com/WR3byT8k
Is there any way I can map this properly to an array so that I can use something simple like:
echo $content['_billing_first_name'];
echo $content['_billing_last_name'];
Which would output:
John
Citizen
Keep in mind all the content is dynamic, so I can’t just use row numbers.
If you have a fixed set of meta keys you need to retrieve (not necessarily a fixed order), you can do it in the query itself by using a technique similar to a pivot table.
The
CASEstatements determine which parameter you are pulling and assign it to a column. They are wrapped inMAX()aggregates simply to eliminate the NULLs which result when the keys don’t match, collapsing it down to a single row with columns for each attribute rather than multiple rows with mostly NULL values.Failing this (if your set of attributes is varies unexpectedly), you would need to iterate in code. That would be messy though.
In PHP:
Using PHP, if you have an array of the meta post keys you want to retrieve, you can loop over all rows and if the
meta_keyis one you want, store themeta_valueonto an array:To get all
meta_key, just leave out thein_array()test and the$keys_you_wantarray. That will store everymeta_keyencountered onto$output.