Skip to content

Instantly share code, notes, and snippets.

@tdmrhn
Last active April 29, 2023 11:26
Show Gist options
  • Save tdmrhn/3870b107cc98443a686d16e0443f64e0 to your computer and use it in GitHub Desktop.
Save tdmrhn/3870b107cc98443a686d16e0443f64e0 to your computer and use it in GitHub Desktop.
Blocksy Blog or CPT live jQuery filter
<script>
jQuery(document).ready(function($) {
$('.ct-filter').on( 'click', function(event){
var $type = $(this).data("filter");
if($type == "all"){
$('.entry-card').fadeOut(0);
$('.entry-card').fadeIn(500);
} else {
$('.entry-card').hide();
// For CPTs just change the category class to your CPTs slug for example: '.projects-'
$('.category-' + $type + '.entry-card').fadeIn(500);
}
});
});
</script>
<!-- For CPTs just change the category slug to your CPTs slug for example: 'projects' -->
<?php
$terms = get_terms(
array(
'taxonomy' => 'category',
'hide_empty' => true,
)
);
if ( ! empty( $terms ) && is_array( $terms ) ) {
?>
<div class="ct-container" data-vertical-spacing="top">
<a data-filter="all" class="ct-button ct-filter">All</a>
<?php
foreach ( $terms as $term ) { ?>
<a data-filter="<?php echo $term->slug; ?>" class="ct-button ct-filter">
<?php echo $term->name; ?>
</a><?php
}
}
?>
</div>
@tdmrhn
Copy link
Author

tdmrhn commented Apr 29, 2023

// vanilla js, i didn't test it yet
document.addEventListener("DOMContentLoaded", function(event) {
  const ctFilters = document.querySelectorAll('.ct-filter');

  for(let i = 0; i < ctFilters.length; i++) {
    ctFilters[i].addEventListener('click', function(event) {
      const type = this.getAttribute('data-filter');
      const entryCards = document.querySelectorAll('.entry-card');
      
      if(type === "all") {
        for(let j = 0; j < entryCards.length; j++) {
          entryCards[j].style.display = 'none';
          setTimeout(function() {
            entryCards[j].style.display = 'block';
          }, 0);
        }
      } else {
        for(let j = 0; j < entryCards.length; j++) {
          entryCards[j].style.display = 'none';
        }
        
        const categoryCards = document.querySelectorAll('.category-' + type + '.entry-card');
        for(let j = 0; j < categoryCards.length; j++) {
          categoryCards[j].style.display = 'block';
        }
      }
    });
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment