Skip to content

Instantly share code, notes, and snippets.

@msaari
Last active July 20, 2020 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msaari/a53aaa57b19a6974096f75ef48208d11 to your computer and use it in GitHub Desktop.
Save msaari/a53aaa57b19a6974096f75ef48208d11 to your computer and use it in GitHub Desktop.
Improved rlv_category_dropdown
<?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