Last active
July 20, 2020 02:53
-
-
Save msaari/a53aaa57b19a6974096f75ef48208d11 to your computer and use it in GitHub Desktop.
Improved rlv_category_dropdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rlv_category_dropdown() { | |
global $rlv_categories_present, $wp_query; | |
$select = "<div id='catCheckboxes'><p>Choose a category:</p>"; | |
$cat_params = array_map( 'intval', explode( ',', $wp_query->query_vars['cats'] ) ); | |
foreach ( $rlv_categories_present as $cat_id => $cat_name ) { | |
$checked = ''; | |
if ( in_array( $cat_id, $cat_params, true ) ) { | |
$checked = "checked='checked'"; | |
} | |
$select .= "<input type='checkbox' name='rlv_cat[]' value='$cat_id' $checked> $cat_name<br />"; | |
} | |
$select .= '</div>'; | |
$url = esc_url(remove_query_arg('paged')); | |
if (strpos($url, 'page') !== false) { | |
$url = preg_replace('/page\/\d+\//', '', $url); | |
} | |
$select .= <<<EOH | |
<script> | |
<!-- | |
var catCheckboxes = document.querySelectorAll("#catCheckboxes"); | |
catCheckboxes.forEach(function(element) { | |
element.addEventListener('change', (event) => { | |
var queryParams = new URLSearchParams(window.location.search) | |
var newCats = [] | |
document.querySelectorAll("#catCheckboxes input").forEach(function(element) { | |
if (element.checked) newCats.push(element.value) | |
}) | |
queryParams.set('cats', newCats.join(',')) | |
history.replaceState(null, null, "?"+queryParams.toString()) | |
}) | |
}) | |
--> | |
</script> | |
EOH; | |
echo $select; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment