I have code that list categories and products by category.
When I click "All" it list all products, but when I go /products page it's not list all products by default and I need to click "All" to get all products. How I can get all products when I go /products page by default without click any category or All -link?
My functions.php
function add_custom_scripts() {
wp_enqueue_script( 'ajax_term', get_stylesheet_directory_uri() . '/ajax/ajax-terms.js', array('jquery'), NULL, true );
wp_localize_script( 'ajax_term', 'wpAjax', array('ajaxUrl' => admin_url('admin-ajax.php')));
}
add_action( 'wp_enqueue_scripts', 'add_custom_scripts' );
Products.php - /products page
<div class="categories">
<ul class="categories-filter" name="categoryfilter">
<li><a type="button" data-posttype="product" class="js-filter-item" href="<?php echo home_url(); ?>">All</a></li>
<?php
if( $terms = get_terms( array(
'taxonomy' => 'product_cat' ) ) ) :
foreach ( $terms as $term ) :
?>
<li>
<a type="button" data-category="<?php echo $term->term_id; ?>"
data-posttype="product"
data-taxonomy="<?php echo $term->taxonomy; ?>" class="js-filter-item" href="<?php echo $term->term_id; ?>" >
<?php echo $term->name; ?>
</a>
</li>
<?php
endforeach;
endif;
?>
</ul>
</div>
<div id="response"></div>
Ajax-terms.js
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item', function(event){
(event).preventDefault();
var category = $(this).data('category');
$.ajax({
url: wpAjax.ajaxUrl,
data: {
action: 'filterterm',
category: category,
taxonomy: $(this).data('taxonomy'),
posttype: $(this).data('posttype')
},
type: 'post',
success: function(result){
$('#response').html(result);
},
error: function(result){
console.warn(result);
}
});
});
});
})(jQuery);
Callback in functions.php
<?php
add_action('wp_ajax_nopriv_filterterm', 'filter_ajax_term');
add_action('wp_ajax_filterterm', 'filter_ajax_term');
function filter_ajax_term(){
$category = $_POST['category'];
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => 'NAME',
'order' => 'ASC'
);
if(isset($category)) {
$args['tax_query'] =
array(
array(
'taxonomy' => $_POST['taxonomy'], //or tag or custom taxonomy
'field' => 'id',
'terms' => array((int)$category)
)
);
}
$the_query = new WP_Query( $args ); ?>
<div class="container">
<?php if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$category = get_the_category();
the_title('<h2>', '</h2>');
endwhile; endif; ?>
</div>
<?php
die();
}
?>