1

I've got a series of custom post types set up, and a large amount of custom fields are linked to these post types via the Advanced Custom Fields plugin.

I want to set up a series of checkboxes on the frontend to filter posts via their custom fields. This is what it looks like at the moment:

enter image description here

And here's the code I'm using to produce it on my archive-books.php page:

<?php $array = array('format', 'bedrooms', 'type'); ?>
<?php foreach ($array as $value):
    $field = get_field_object($value);
    $values = explode(',', $_GET[$value]);
?>
    <div id="<?php echo $value; ?>" class="filter">
        <h3><?php echo $value; ?></h3>
        <ul class="<?php echo $value; ?>">
            <?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
                <li>
                    <input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endforeach; ?>

Now this works great! I define the custom fields I want to pull filters in for with that array at the top. And I'm using some Javascript to edit my URL depending on the selections made by the user (like shown in the screenshot above). Here's my JS:

<script type="text/javascript">
    (function($) {
        $('#format').on('change', 'input[type="checkbox"]', function(){
            var $ul = $(this).closest('ul'),
                vals = [];
            $ul.find('input:checked').each(function(){
                vals.push( $(this).val() );
            });
            vals = vals.join(",");
            window.location.replace('<?php echo home_url('books'); ?>?format=' + vals);
        });
    })(jQuery); 
</script>

What I'm trying to work out is how to dynamically alter that Javascript. So instead of "format" it uses the custom fields from my $array. This also needs to take into account multiple filters, so the URL would look like this:

dev.website.com/books?format=paperback&type=home,men

If anyone could help with the Javascript, I'd really appreciate it. I've tried to include it in the foreach loop, but no dice.

Any help is appreciated! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.