Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ben-heath/7891e59198701dc66a07ef4ecae89753 to your computer and use it in GitHub Desktop.
Save ben-heath/7891e59198701dc66a07ef4ecae89753 to your computer and use it in GitHub Desktop.
FacetWP - show template only if a facet is selected
<?php
/* This code goes into your child theme's function.php file
* Or it can use FacetWP's recommendation and use a plugin https://facetwp.com/how-to-use-hooks/
*
* I found that the tutorial on FacetWP's site didn't function how I wanted it to.
* https://facetwp.com/how-to-hide-the-template-until-facets-are-selected/
* Their method doesn't allow a template to show if you use a link with a url query, indicating a facet selection, it only works if
* if you 'click' on the page. So I came up with some JS that looks at the facet list, and looks for any 'checked' items.
* This way, whether it was clicked while on the page, or you linked to the page with a query string selection, it still works as I wanted.
*/
add_action( 'wp_footer', function() {
?>
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
// selector is dependent on what you're targeting
if ($('.facetwp-facet.facetwp-facet-ssl_categories.facetwp-type-radio').find('.checked').length == 1) {
$('.facetwp-template').addClass('visible');
}
else {
$('.facetwp-template').removeClass('visible');
}
});
})(jQuery);
</script>
<?php
}, 100 );
?>
.facetwp-template { display: none; }
.facetwp-template.visible { display: block; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment