Support

Account

Home Forums ACF PRO Filtering by relationship field in pre_get_posts on post archive page Reply To: Filtering by relationship field in pre_get_posts on post archive page

  • Hmmm, spoke too soon. My code now works fine on post archive pages, but I need to add it to the CPT “events” as well, which uses the exact same set of custom fields. But this isn’t working. I can test and see that it is correctly triggering the various if statements, but it doesn’t seem that the meta query gets applied – it just returns all results, unfiltered. Posts are still working, though, with the exact code below. Does this sort of meta query get applied differently to a CPT than to the standard post?

    function query_by_relationship( $query ) {
        
        if( is_admin() ) {
            return $query;
        }
    
        if ((is_archive() && $query->is_main_query()) || ( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'events' ) ) { 
            
            if( isset($_GET['sector']) ) {
                $meta_query = array(
                                array(
                                    'key'       => 'related_industries',
                                    'value' => '"' . $_GET['sector'] . '"',
                                    'compare'   => 'LIKE',
                                )
                            );
                $query->set('meta_query', $meta_query);
            } else if( isset($_GET['pa']) ) {
                $meta_query = array(
                                array(
                                    'key'       => 'related_practice_areas',
                                    'value' => '"' . $_GET['pa'] . '"',
                                    'compare'   => 'LIKE',
                                )
                            );
                $query->set('meta_query', $meta_query);
            } else if( isset($_GET['lawyer']) ) {
                $meta_query = array(
                                array(
                                    'key'       => 'related_people',
                                    'value' => '"' . $_GET['lawyer'] . '"',
                                    'compare'   => 'LIKE',
                                )
                            );
                $query->set('meta_query', $meta_query);
            }
            
        }
        
        
        // return
        return $query;
    
    }
    
    add_action('pre_get_posts', 'query_by_relationship');