【发布时间】:2020-06-02 08:36:23
【问题描述】:
我想使用 AJAX 为 Woocommerce 创建自己的产品过滤器,我不想使用任何插件。但是有一个问题,我不知道如何通过所选过滤器获取产品,或者我不知道我的过滤器将如何应用于产品。
例如,如果我想为评分设置一个过滤器。
HTML
<select id="filter_ratings">
<option value="5">5 star</option>
<option value="4">4 star</option>
<option value="3">3 star</option>
<option value="2">2 star</option>
<option value="1">1 star</option>
</select>
jQuery
jQuery('#filter_ratings').change(function() {
var values = jQuery(this).val();
jQuery.ajax({
url: ajax_object.ajax_url,
method: 'POST',
data: {opc: values, action: 'filter_product_by_ratings', dataType: "json"},
success: function(result){
//Should I get all the products with the current filter?
console.log('Filter Successful: ' + result);
},
error:function (xhr, ajaxOptions, thrownError) {
console.log('Filter ERROR STATUS: ' + xhr.status);
console.log('Filter Error: ' + thrownError);
}
});
});
function.php
add_action('wp_enqueue_scripts', 'add_js_scripts');
function add_js_scripts(){
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//call this function by ajax
function filter_product_by_ratings(){
//what now?
//How can I apply the current filter?
//Should I fetch all the products by the current filter?
//What about for other attributes like size, color, etc?
}
是否有关于如何在 Woocommerce 中按代码对产品应用过滤器的指南?
【问题讨论】:
-
使用 ajax 过滤产品需要先用 ajax 加载产品...
标签: php jquery ajax wordpress woocommerce