Skip to content

Instantly share code, notes, and snippets.

@andrearufo
Last active July 3, 2019 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrearufo/e036bb8afbede846d8cc5cf5c903a439 to your computer and use it in GitHub Desktop.
Save andrearufo/e036bb8afbede846d8cc5cf5c903a439 to your computer and use it in GitHub Desktop.
Normalize a Wordpress MySQL table with post meta value
<?php
/**
* 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
WHERE
( ";
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