Creating a table from another’s results using WP $wpdb functions

Question

Below is the query and function I use to create a table from another table’s results:

$mytable = "myCustomTable";

$thisSQL = "SELECT p.ID, p.post_title, p.post_author, p.post_status, 
COALESCE( ( SELECT meta_value FROM wp_postmeta pm WHERE pm.post_id = p.ID AND pm.meta_key = 'metakey1' ), '' ) as metakey1, 
COALESCE( ( SELECT meta_value FROM wp_postmeta pm WHERE pm.post_id = p.ID AND pm.meta_key = 'metakey2' ), '' ) as metakey2, 
COALESCE( ( SELECT meta_value FROM wp_postmeta pm WHERE pm.post_id = p.ID AND pm.meta_key = 'metakey3' ), '' ) as metakey3, 
GROUP_CONCAT(DISTINCT t.name ORDER BY t.name DESC SEPARATOR ', ') as terms FROM wp_posts p 
LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID 
LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id 
LEFT JOIN wp_terms t ON t.term_id = tax.term_id 
WHERE p.post_type = 'projects' AND p.post_status NOT IN ('auto-draft','draft', 'inherit') 
GROUP BY p.ID;";

/*This is the query that makes a table from another table results*/
$create_sql  = "CREATE TABLE " . $mytable. "(" . $thisSQL . ");";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
maybe_create_table( $mytable,  $create_sql );

Is there a better way to create a table form another’s results using $wpdb functions?

If so, how can a row be updated using using the same method?

0
, , samjco 4 years 2019-11-02T01:01:10-05:00 0 Answers 101 views 0

Leave an answer

Browse
Browse