Support

Account

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

  • 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(
                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'); }