Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Normalize a Wordpress MySQL table with post meta value
* Return the normalized collection of posts with custom fields
* @param string $type The custom post name
* @param array $infos The list of custom post types required
* @return array A collection of post object normalized
function wp_custom_post_normalized_table($type, $infos = []){
global $wpdb;
$query = "SELECT ID, post_title as title";
foreach($infos as $info){
$query .= ", MAX( CASE WHEN pm.meta_key = '".$info."' THEN pm.meta_value END ) AS ".$info." ";
$query .= "FROM
{$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
( ";
foreach($infos as $info){
$x[] = "pm.meta_key = '".$info."' ";
$query .= implode(' OR ', $x);
$query .=")
AND pm.meta_value IS NOT NULL
AND p.post_status = 'publish'
AND p.post_type = '".$type."'
GROUP BY pm.post_id";
// return $query;
$normalized = $wpdb->get_results($query);
return $normalized;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.