我有按类别列出类别和产品的代码。
当我单击" all "时,它列出了所有产品,但当我进入/ products 页面时,默认情况下它并不列出所有产品,我需要单击“all”
我的<#>函数.
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页面
All
'product_cat' ) ) ) :
foreach ( $terms as $term ) :
?>
name; ?>
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);
functions.php s.php中的回调
'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 ); ?>
have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$category = get_the_category();
the_title('', '');
endwhile; endif; ?>发布于 2021-01-19 15:56:29
首先,您应该为前端使用REST,而不是admin。第二,不应使用未经筛选的POST值。对于页面加载的产品,当ID存在时,您应该告诉Javascript填充ID "response“。现在,您只加载产品,当类js item上的click事件发生时。使用像这样的辅助函数来尝试它。
(function($){$(document).ready(function(){
if ($('#response').length){
function load_all_products() {
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);
}
});
}
load_all_products();
$('.js-filter-item').on('click', function(event){
(event).preventDefault();
load_all_products();
});
})(JQuery);
这是未测试的,不会通过复制和粘贴来工作,但是也许你有了这个想法。当ID "response“存在时,调用函数load_all_products()。当您单击带有“js item”类的筛选器时,使用所选的按钮/筛选器/任何东西调用此函数。您可能必须更改$(this).data(xxx)调用以更正值。对于分页,您必须添加页变量。
https://wordpress.stackexchange.com/questions/381759
复制相似问题