Support

Account

Home Forums General Issues Post Object – Query filter for both title and/or meta value Reply To: Post Object – Query filter for both title and/or meta value

  • I couldn’t get any of the published methods working with ACF. Using the adambelee link, the WHERE clause was always empty. However, got it working by combining ACF query filter with a WP WHERE override to turn the search AND meta into search OR meta.

    Essentially, WP Query is missing a meta_query_relation option (and tax_query_relation for that matter) and this code adds one!

    /*
     * Allow breaker search by make/model or VRN. Requires two parts:
     * 1. Inject meta-query for VRN, plus custom query param to trigger part 2
     * 2. Modify final query to OR the meta_query instead of AND
     * Basically add the missing WordPress query_var!
     */
    
    // Part 1
    add_filter('acf/fields/post_object/query/name=part_breaker', 'motor_vrn_search_query1', 10, 3);
    function motor_vrn_search_query1( $args, $field, $post_id) {
    
    	if (isset($args['s'])) { 
    		$args['meta_query'] = array(
    			'relation' => 'OR',
    			array(
    				'key' => 'motor_id_motor_vrn',
    				'value' => $args['s'],
    				'compare' => 'LIKE'),
    		);
    		$args['_meta_query_relation'] = 'OR'; // Custom query param
    	}
    	
    	return $args;
    }
    
    // Part 2: Modify the search query with posts_where
    add_filter( 'posts_where', 'motor_vrn_search_query2', 10, 2);
    function motor_vrn_search_query2( $where, $query) {
        global $pagenow, $wpdb;
    
    	$mq_relation = (isset($query->query_vars['_meta_query_relation']) ? $query->query_vars['_meta_query_relation'] : '');
    	if ($mq_relation === 'OR') { // WordPress defaults to AND
            $where = preg_replace(
                "/\)\)\)\s*AND \(\s*\(\s*".$wpdb->postmeta.".meta_key/",
                "))) OR (( ".$wpdb->postmeta.".meta_key",
    			$where
    		);
        }
    
        return $where;
    }