In wordpress I often use $wpdb to just do my queries manually when I just need to extract some value.
In my case, I have a Membrepress rule that could be tied to some content type. The rule’s meta includes two keys that I am trying to query on: _mepr_rules_type
and _mepr_rules_content
.
I know I can do something like this:
$args = array(
'post_type' => 'memberpressrule',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_mepr_rules_content',
'value' => 885,
'compare' => '='
),
array(
'key' => '_mepr_rules_type',
'value' => 'single_sfwd-lessons',
'compare' => '='
)
)
);
$results = new WP_Query($args);
But it seems overkill when I simply want the rule id.
I see that WordPress is constructing the query as
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND (
( wp_postmeta.meta_key = '_mepr_rules_content' AND wp_postmeta.meta_value = '885' )
AND
( mt1.meta_key = '_mepr_rules_type' AND mt1.meta_value = 'someruletype' )
) AND wp_posts.post_type = 'memberpressrule' AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 34 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC
Is there any reason to deal with WP_Query? I mean, I really don’t want to deal with resetting global $post and other headaches that one ends up with when using queries inside an existing post loop. So would doing this manual query be the fastest way?
global $wpdb;
$sql = "SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND (
( wp_postmeta.meta_key = '_mepr_rules_content' AND wp_postmeta.meta_value = '885' )
AND
( mt1.meta_key = '_mepr_rules_type' AND mt1.meta_value = 'someruletype' )
) AND wp_posts.post_type = 'memberpressrule' AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 34 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC"
$results = $wpdb->get_results($sql);
Also, any reason why I need to join on wp_posts, if the wp_postmeta table itself contains the data I need?
Curious if anyone has ideal method to extract the sort of data I am trying to retrieve.
Thanks!