Home Forums General Issues Adjust main query based on taxonomy of "Relationship" related posts


Adjust main query based on taxonomy of "Relationship" related posts

  • How’s that for a confusing title?

    What I need to do is filter the query of a custom post type based on whether any of the posts in an ACF “Relationship” field have a particular taxonomy term on them.

    Here’s a more exact description of the scenario:

    I have a CPT of “Products”, and they have a “Relationship” ACF field called “Display Rules”. These rules have a taxonomy, “Countries”.

    Before showing products I need to test whether any of the rules in the relationship field have a Country taxonomy term that matches a value set elsewhere, and if so, exclude them from the query.

    I’m not sure that’s any clearer, but that’s what I need to do. Can anyone help?

  • I solved it, for the most part. Here’s what worked for me:

        * Filter the query using the rules
    // Get all the rules that have a taxonomy term that match the visitor's GEO-IP-detected country 
    function get_relevent_rules() {
         $args = array(
            'numberposts' => '-1',
    	    'post_type'   => 'display_rule',
            'tax_query'   => array(
                    'taxonomy' => 'my_taxonomy',
                    'terms' => 'A_GLOBAL_SET_ELSEWHERE_TO_THE_VISITORS_COUNTRY_OF_ORIGIN',      
                    'field' => 'slug',
        $return = array();
        foreach (wp_list_pluck( get_posts($args), 'ID') as $id) {
            $return[] = array(
                        'key'       => 'display_rules',
                        'value'     => '"' . $id . '"',
                        'compare'   => 'NOT LIKE',
        return $return;
    // Change the main query to exclude any posts with a relationship field keyed 'display_rules' which includes any of the display rules containing our visitor's country.
     function only_in_countries($query) {
        if ($query->is_main_query()) {
            $query->set( 'meta_query', get_relevent_rules()
    if( ! is_admin()) { add_action('pre_get_posts', 'only_in_countries'); } 
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Adjust main query based on taxonomy of "Relationship" related posts’ is closed to new replies.