Last active
February 7, 2021 20:06
-
-
Save edirpedro/66c7c50e0983942a45aac5edb2ea0620 to your computer and use it in GitHub Desktop.
Some ideias to create Views Tables from WordPress data in case you need to make custom queries in the database.
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 | |
function _create_views() { | |
global $wpdb; | |
/* | |
* Post Type book and its ACF custom fields | |
*/ | |
$sql = " | |
CREATE OR REPLACE VIEW view_books AS | |
SELECT | |
p.ID AS ID, | |
p.post_title as post_title, | |
p.post_content as post_content, | |
pm1.meta_value AS author, | |
pm2.meta_value AS isbn, | |
pm3.meta_value AS pictures | |
FROM wp_posts p | |
INNER JOIN wp_postmeta pm1 ON ( pm1.post_id = p.ID AND pm1.meta_key = 'author' ) | |
INNER JOIN wp_postmeta pm2 ON ( pm2.post_id = p.ID AND pm2.meta_key = 'isbn' ) | |
INNER JOIN wp_postmeta pm3 ON ( pm3.post_id = p.ID AND pm3.meta_key = 'pictures' ) | |
WHERE p.post_type = 'book' | |
"; | |
$wpdb->query($sql); | |
/* | |
* Books attributes "Repeater Field" | |
* | |
* The trick is to use the first sub field to return the length of the repeater, | |
* then use inner join to get the other sub fields to map as columns. | |
*/ | |
$sql = " | |
CREATE OR REPLACE VIEW view_books_attributes AS | |
SELECT | |
pm1.post_id AS post_id, | |
pm1.meta_value AS name, | |
pm2.meta_value AS value | |
FROM wp_postmeta pm1 | |
INNER JOIN wp_postmeta pm2 ON ( pm2.post_id = pm1.post_id AND pm2.meta_key = REPLACE( pm1.meta_key, '_name', '_value' ) ) | |
WHERE pm1.meta_key LIKE 'book_attributes_%_name' | |
"; | |
$wpdb->query($sql); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment