Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set checkbox state based on value

I am creating a taxonomy filter for WordPress archives. I have the checkboxes working so when selected they redirect the page to the correct URL based on the taxonomy slug. My problem is that after page reload the checkbox state resets to unchecked.

Here is my code:

<?php
$workoutmoves = get_terms('Exercise-Types', array('hide_empty' => 0));
?>

<?php if ($workoutmoves): ?>
<h5>Show Me</h5>
<ul class="no-bullet">
    <?php foreach($workoutmoves AS $workoutmove): ?>
    <li>
        <input class="check_box" type="checkbox" value="<?php echo $workoutmove->slug; ?>"><?php echo $workoutmove->name; ?>
    </li>
    <?php endforeach; ?>
</ul>
<?php endif; ?>

I thought of adding a php if statement into the input field and echoing 'checked="checked"' but I don't know how to grab the correct data to identify if it should be set.

Any insights would be a huge help. Thanks.

like image 380
kslambert Avatar asked Jul 19 '26 01:07

kslambert


1 Answers

You just need to get the current taxonomy term using get_queried_object() wp function and change your loop a like this:

    <?php $term_id = get_queried_object()->term_id; #getting current term_id ?>
    <?php foreach($workoutmoves AS $workoutmove): ?>
    <li>
        <input class="check_box" type="checkbox" 
        <?php $workoutmove->term_id==$term_id?'checked':''; ?>
        value="<?php echo $workoutmove->slug; ?>">
        <?php echo $workoutmove->name; ?>
    </li>
    <?php endforeach; ?>
like image 78
Tom Sarduy Avatar answered Jul 21 '26 23:07

Tom Sarduy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!