How do I query taxonomy OR custom field in Wordpress at the same time? -
i need query wordpress posts returning results matched either category or custom field. using below code returns results if matched category , custom field. need find matches matched either query, "or" result doesn't seem work.
can help?
$args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'or', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( 'arts','food' ), 'operator' => 'in' ) ), 'meta_query' => array( 'relation' => 'or', array( 'key' => 'birth_city', 'value' => 'london', 'compare' => 'in', ), ) );
version 0.2
here's simplification of previous answer - hope don't mind me adding new answer, avoid confusion previous one.
here use wordpress functions get_meta_sql()
, get_tax_sql()
, modify where
part of sql generated wp_query()
:
/** * class wpse_or_query * * add support (tax_query or meta_query) * * @version 0.2 * @link http://stackoverflow.com/a/22633399/2078474 * */ class wpse_or_query extends wp_query { protected $meta_or_tax = false; protected $tax_args = null; protected $meta_args = null; public function __construct( $args = array() ) { add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ), 999 ); add_filter( 'posts_where', array( $this, 'posts_where' ), 999 ); parent::__construct( $args ); } public function pre_get_posts( $qry ) { remove_action( current_filter(), array( $this, __function__ ) ); // query vars $this->meta_or_tax = ( isset( $qry->query_vars['meta_or_tax'] ) ) ? $qry->query_vars['meta_or_tax'] : false; if( $this->meta_or_tax ) { $this->tax_args = ( isset( $qry->query_vars['tax_query'] ) ) ? $qry->query_vars['tax_query'] : null; $this->meta_args = ( isset( $qry->query_vars['meta_query'] ) ) ? $qry->query_vars['meta_query'] : null; } } public function posts_where( $where ) { global $wpdb; $field = 'id'; remove_filter( current_filter(), array( $this, __function__ ) ); // construct "tax or meta" query if( $this->meta_or_tax && is_array( $this->tax_args ) && is_array( $this->meta_args ) ) { // tax query $sql_tax = get_tax_sql( $this->tax_args, $wpdb->posts, $field ); // meta query $sql_meta = get_meta_sql( $this->meta_args, 'post', $wpdb->posts, $field ); // modify 'where' part if( isset( $sql_meta['where'] ) && isset( $sql_tax['where'] ) ) { $where = str_replace( array( $sql_meta['where'], $sql_tax['where'] ) , '', $where ); $where .= sprintf( ' , ( %s or %s ) ', substr( trim( $sql_meta['where'] ), 4 ), substr( trim( $sql_tax['where'] ), 4 ) ); } } return $where; } }
Comments
Post a Comment