Support

Account

Forum Replies Created

  • 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');
    
  • Well, this is awkward. I had taken that code out of functions.php to try things another way. I pasted back in my code from above, tweaked a few var names as needed, and it worked perfectly fine (whether or not I had the [] in, tried it both ways). So whatever the problem in the code was, it must have been one of the extra bits that I had in there before stripping it down to post on the forum!

    Thanks anyway for your response, apparently I just needed a sounding board 😉

Viewing 2 posts - 1 through 2 (of 2 total)