Support

Account

Home Forums Front-end Issues Exclude custom posts from pre_get_posts based on custom field

Solving

Exclude custom posts from pre_get_posts based on custom field

  • Hi
    I would like to exclude posts with via the url based on a custom field and I followed this:

    https://www.advancedcustomfields.com/resources/query-posts-custom-fields/
    and “Dynamic $_GET parameters” which works but not if I want to exclude the post with the value.

    I have a custom field called ‘members_only_video’ which is a True/False.

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	}
    	
    	// only modify queries for 'webinar' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'webinar' ) {
    		
    		// allow the url to alter the query
    		if( isset($_GET['members_only_video']) ) {
                
                $query->set('meta_query', array(
                    array(
                        'key' => 'members_only_video',
                        'value' => $_GET['members_only_video'],
                        'compare' => '!=',
                )));
    
                
        	} 
    		
    	}
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');
  • I came a bit on the way to finding a solution.

    I change the compare to:
    ‘compare’ => ‘NOT EXISTS’

    and the query now returns the right posts but it ignores the =true =false values
    The urls:
    http://www.website.com/events?city=true
    http://www.website.com/events?city=false
    just returns the same?

  • 
    $meta_query = array(
    	'relation' => 'AND',
    	array(
    		'key' => 'members_only_video',
    		'compare' => 'EXISTS'
    	),
    	array(
    		'key' => 'members_only_video',
    		'value' => $_GET['members_only_video'],
    		'compare' => '!='
    	)
    );
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.