Support

Account

Home Forums General Issues Filtering Archives Using Checkbox Custom Fields

Solved

Filtering Archives Using Checkbox Custom Fields

  • I’ve had a read of the documentation over here regarding creating an archive with a custom field filter, but was wondering how I would apply this same logic when using the Checkbox Field, as opposed to a Radio Field?

    My Checkbox Field is called ‘type’ and has seven values. Would this be possible?

    I’ve tried using the meta_query ‘LIKE’, but still no dice.

    Any help is appreciated. Thanks a bunch!

  • OK, so I’m using an array for my checkboxes, and am using the pipe ‘|’ character instead of commas.

    Now, when I manually add my custom fields and separate them in the url like so:

    dev.com/slug?=field1|field2|field3

    this checks the appropriate checkboxes, but doesn’t return the filtered post results. Is there a different method, when using checkboxes?

  • Hi @realph

    Please note that the referenced tutorial is an example, and shoudl not be used literaly in all scenarios.

    Please read the checkbox docs to see how the LIKE compare is needed to search within an array value:
    http://www.advancedcustomfields.com/resources/field-types/checkbox/

    Your $_GET param looks good (didn’t this start on another tread? If so, can we please keep all conversations within the same thread). You need to explode the $_GET param to obtain an array of all checkbox values, then loop over them and construct WP_Query args.

    Good luck.

    Thanks
    E

  • @elliot Shouldn’t exploding and dumping my $_GET param return my seven checkbox values for the custom field ‘type’? When I do var_dump($wp_query->query_vars); it prints an array with 62 items. 😐

    Sorry if I’ve created a new thread entirely. I can’t seem to find the one you’re referencing.

  • @elliot *Exhale* I feel to cry! After a whole day of staring at my functions.php, I think I may have finally cracked it!

    add_action('pre_get_posts', 'my_pre_get_posts');
     
    function my_pre_get_posts( $query ) {
    	if( is_admin() ) {
    		return;
    	}
     
    	$book_format = $query->get('meta_query');
     
            if( !empty($_GET['type']) ) {
            
    	    	$book_format[] = array(
                    'key'		=> 'type',
                    'value'		=> $_GET['type'],
                    'compare'	=> 'LIKE',
                );
            }
     
    	$query->set('meta_query', $book_format);
     
    	return;
    }

    Now when I append this to my url:

    dev.com/books?=home

    it displays an archive of all my books with the ‘type’ of ‘home’. This is fantastic!

    The only problem I’m having now is, separating these in the url with the ‘|’ character doesn’t seem to yield any results. Any idea why that might be happening, or is that normal?

  • Ok, false alarm. The code above was wrong. @elliot Some people over on the Stack Exchange forum are saying I shouldn’t be using a LIKE compare, and an IN instead when using arrays.

    Not sure which is right. But when I try to use an IN compare, I get a blank page when querying my posts.

    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');
            if( !empty($_GET['type']) ) {				
            	$type = explode('|', $_GET['type']);	
    
    	    	$meta_query[] = array(							
                    'key'		=> 'type',
                    'value'		=> $type,
                    'compare'	=> 'IN',
                );
            }
    	$query->set('meta_query', $meta_query);
    	return;	// always return
    }
    
  • @elliot Do you think this has anything to do with the serialized data the Checkbox Field outputs?

    Some of my books are assigned to multiple Book Types, like so:

    Book Title: Mums and Babies
    Book Type:

    • Women
    • Babies
    • Children

    Wondering if this is what’s causing the issue.

    This is where I’m at currently:

    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
            
            if( isset($_GET['type']) ) {                        
            
            $type = '"' . $_GET['type'] . '"';      
    
            $meta_query[] = array(
                'key'       => 'type',
                'value'     => $type,
                'compare'   => 'LIKE',
            );
        }
        $query->set('meta_query', $meta_query); // update the meta query args
        return; // always return
    }

    Works with one value, but not multiple values (.com/?type=women,babies):

  • 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

  • Hi @elliot,

    Thanks for this! That was really helpful and makes complete sense now. One issue I’m running into though, is the website begins to hang when you query more than three types. Do you know of any reason why that could be?

  • Hi @realph

    I can’t give you an exact answer, but please always debug your data to find out why it doesn’t work as expected. Debug your $args after they have been populated.

    Thanks
    E

  • @elliot No worries! Going to do some debugging tonight. Thanks for all your help and once again thank you for the awesome plugin. It is THE plugin that turns WordPress into a “true” CMS!

  • This reply has been marked as private.
  • Hello @realph-

    I was wondering if you could share the code on your archive template that generates the front end filter? I am having an issue where the checkboxes aren’t displaying on my archive form. Just wanted to compare your code to mine.

  • This reply has been marked as private.
Viewing 14 posts - 1 through 14 (of 14 total)

The topic ‘Filtering Archives Using Checkbox Custom Fields’ is closed to new replies.