Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Woo filter for sub category
- */
- class HbWooAjaxFilterSubCat {
- function __construct() {
- add_action( 'init', [ $this, 'ajax_init' ] );
- }
- public function ajax_init() {
- add_action( 'wp_enqueue_scripts', array( $this, 'woo_cat_filter_ajax_vars' ) );
- if ( wp_doing_ajax() ) {
- add_action( 'wp_ajax_hb_ajax_filter', [ $this, 'filter' ] );
- add_action( 'wp_ajax_nopriv_hb_ajax_filter', [ $this, 'filter' ] );
- }
- }
- public function woo_cat_filter_ajax_vars() {
- if ( is_product_category() ) {
- $category = get_queried_object();
- $cat_id = $category->term_id;
- } else {
- $cat_id = 'none';
- }
- wp_localize_script( 'conj-scripts', 'hbFilterCat', [
- 'url' => admin_url( 'admin-ajax.php' ),
- 'cat_id' => $cat_id
- ] );
- }
- public function filter() {
- $filters = $_POST['filter'];
- $cat_id = (int) $_POST['cat'];
- if ( ! empty( $filters ) ) {
- $filter_query = $this->getFilter( $filters, $cat_id );
- // var_dump( $filter_query );
- $query = new WP_Query( [
- 'post_type' => 'product',
- 'tax_query' => [
- 'relation' => 'AND',
- $filter_query,
- ]
- ] );
- if ( $query->have_posts() ) {
- while ( $query->have_posts() ) {
- $query->the_post();
- wc_get_template_part( 'content', 'product' );
- }
- } else {
- echo __( 'No products found' );
- }
- wp_reset_postdata();
- wp_die();
- }
- wp_die();
- }
- public function getFilter( $filters, $cat_id ) {
- $filter_query = [];
- foreach ( $filters as $filter ):
- if ( ! empty( $filter['checked'] ) ) :
- $checked = [];
- foreach ( $filter['checked'] as $filchecked ):
- $checked[] = (int) $filchecked;
- endforeach;
- $filter_query[] = [
- 'taxonomy' => $filter['termName'],
- 'field' => 'id',
- 'terms' => $checked,
- ];
- endif;
- endforeach;
- $filter_query[] = [
- 'taxonomy' => 'product_cat',
- 'field' => 'id',
- 'terms' => $cat_id
- ];
- return $filter_query;
- }
- }
- new HbWooAjaxFilterSubCat();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement