samedi 1 avril 2017

Changing checkbox to a button to filter wordpress posts

I have just added some code to my archive template in order to filter posts by a custom field using checkboxes...this is all working fine however I would like to have buttons instead of checkboxes so I'm wondering if this possible?

This is my code for the post filter:

<div id="search-houses">

<?php 

    $field = get_field_object('purchase');
    $values = isset($_GET['purchase']) ? explode(',', $_GET['purchase']) : array();

?>

    <ul>
        <?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>
            <?php endforeach; ?>
    </ul>

</div>

there is also some javascript to update the url if this is needed?

<script type="text/javascript">

(function($) {

$('#search-houses').on('change', 'input[type="checkbox"]', function(){

    // vars
    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('property'); ?>?purchase=' + vals);

    console.log( vals );

});

})(jQuery);




Aucun commentaire:

Enregistrer un commentaire