Last active
July 3, 2019 15:28
-
-
Save andrearufo/e036bb8afbede846d8cc5cf5c903a439 to your computer and use it in GitHub Desktop.
Normalize a Wordpress MySQL table with post meta value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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