WP_QUERY:如何对元值进行排序并使用左联接?

时间:2016-04-22 作者:Kaah

我使用Wordpress 4.5,并试图修改查询以使用左连接而不是内部连接。但我不能\'relation\' => \'OR\' 工作。请参见下面的查询。我已经读了很多其他关于这方面的帖子,但我不能正确理解。

$premium_args = array(
        \'meta_query\' => array(\'relation\' => \'OR\', array( \'key\' => \'premium\', \'value\' => \'1\', \'compare\' => \'=\' )),
        \'tax_query\' => array( array( \'taxonomy\' => \'posts-from\', \'field\' => \'id\', \'terms\' => $term->term_id ) ),
            \'post_type\' => \'post\',
        \'posts_per_page\' => $posts_per_page,
        \'meta_key\' => \'verified\',
        \'orderby\' => \'meta_value_num\',
        \'order\' => \'DESC\',
        \'paged\' => $paged
    );
    $premium = new WP_Query( $premium_args);
下面是查询结果。如何强制它使用左连接?

REQUEST:SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 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_term_relationships.term_taxonomy_id IN (7)
) AND ( 
  wp_postmeta.meta_key = \'verified\' 
  AND 
  ( 
    ( mt1.meta_key = \'premium\' AND CAST(mt1.meta_value AS CHAR) = \'1\' ) 
    OR 
    ( mt1.meta_key = \'verified\' AND CAST(mt1.meta_value AS CHAR) = \'1\' )
  )
) AND wp_posts.post_type = \'post\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 25

1 个回复
SO网友:user5200704

Wordpress还提供了更多过滤器来更改自定义查询。https://codex.wordpress.org/Custom_Queries

add_filter(\'posts_join\', \'custom_query_join\' );
$premium = new WP_Query( $premium_args);
remove_filter(\'posts_join\', \'custom_query_join\' ); // remove filter bcz not effect to another query to use after this query.

function custom_query_join( $join ){
  $join .= \'Put here join to table\';
  return $join;
}