Support

Account

Home Forums General Issues Filtering Archives Using Checkbox Custom Fields Reply To: Filtering Archives Using Checkbox Custom Fields

  • Hi @realph

    Yes, becuase ACF is saving the checked values as a serialized array, the ‘IN’ compare will not work. The IN compare is used when the database value is a single string value, and the value used in the $meta_query is an array. This is not the data setup you have, so you should not use this.

    The pseudo code for this query is:

    
    get all posts where the meta_value for is 'a' or 
    the meta_value for is 'b' or
    the meta_value for is 'c'
    

    You can write this like so:

    
    <?php 
    
    add_action('pre_get_posts', 'my_pre_get_posts');
     
    function my_pre_get_posts( $query ) {
    
        if( is_admin() ) { return; }
     
        $meta_query = $query->get('meta_query'); // get original meta query
        
        
        // validate type
        if( empty($_GET['type']) )
        {
    	    return;
        }
        
        
        // get types as an array
        // - use explode to get an array of values from type=a|b|c
        $types = explode('|', $_GET['type']);
        
        
        // set compare for the meta_query
        // - http://codex.wordpress.org/Class_Reference/WP_Query
        $meta_query['relation'] = 'OR';
        
        
        foreach( $types as $type )
        {
    	    $meta_query[] = array(
                'key'       => 'type',
                'value'     => '"' . $type . '"',
                'compare'   => 'LIKE',
            );
        }
    	
    	
        $query->set('meta_query', $meta_query); // update the meta query args
        
        return; // always return
    }
    
    ?>
    

    Hope that helps

    Thanks
    E