Home Forums General Issues Filter posts via URL Parameter with Checkbox Values


Filter posts via URL Parameter with Checkbox Values

  • I’m trying to filter posts on a page via URL parameter by an ACF checkbox field. I have successfully done this using a select field with the following code:

    function my_pre_get_posts( $query ) {
        if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {
            if( isset($_GET['wine_style']) ) {
                $query->set('meta_key', 'wine_style');
                $query->set('meta_value', $_GET['wine_style']);
         } // if post_type == product
    	return $query;
    add_action('pre_get_posts', 'my_pre_get_posts'); //Allow for query string in URL for product style ACF field (red, sparkling, etc.)

    The above code works and it is filtering my custom post type of “product” with the ACF select field of “wine_style”. In this field there are various values of “red”, white”, “sparkling” etc so when you go to the URL of “/shop?wine_style=white” it only shows white.

    I am trying to do the exact same thing by setting the meta values but for a different field with a checkbox.

  • Guessing that your select field only stores on value, this means that it is a simple text value in the DB.

    A checkbox field is stored as a serialized array in the DB, the same would happen for a select field that allows multiple values. To search by this field meta_compare must be LIKE

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

You must be logged in to reply to this topic.