如何使用AJAX创建Woocommerce产品过滤器?

时间:2020-06-02 08:36:23

标签: php jquery ajax wordpress woocommerce

我想用AJAX创建自己的Woocommerce产品过滤器,我不想使用任何插件。但是,有一个问题,我不知道如何通过选定的过滤器获取产品,或者我不知道我的过滤器将如何应用于产品。

例如,如果我想为“收视率”设置过滤器。

HTML

SEED = 42
n_classes = 24

test_df = pd.read_csv(TEST_PATH)

test_df = [test_df.loc[test_df.label==i].sample(n=int(2000/n_classes),random_state=SEED) for i in test_df.label.unique()]
test_df = pd.concat(test_df, axis=0, ignore_index=True)

val_df,test_df = train_test_split(test_df,test_size=0.5,random_state=SEED,stratify=test_df['label'])

jQuery

<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>

function.php

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);
            } 
        });
    });

是否有关于如何在Woocommerce中通过代码将过滤器应用于产品的指南?

1 个答案:

答案 0 :(得分:1)

首先,您将错误ajax_object命名为undefinedObject not found,因为您没有正确定位它。

查看ajax网址ajax_objectajax_url,在函数中将其本地化为ajax_objectajaxurl。您只是错过了ajax URL中的下划线,它应该是ajax_object.ajaxurl

有关如何正确定位的信息,请参阅下面的链接。 https://developer.wordpress.org/reference/functions/wp_localize_script/

关于如何过滤产品的问题,可以使用WP_Query,然后根据需要更改参数。例如,由于您只想获取产品,因此post_type应该为product,而其他参数会根据您的需求而变化,例如orderbyratings等。< / p>

以下是function.php中缺少的代码示例。

function filter_products(){

    $select_opc = $_POST['opc']; //here is your post data, you can use its value to filter the products

    $args = array('post_type' => 'product','posts_per_page' => 12); //change this arguments depending on your needs
    $loop = new WP_Query( $args );
    $products = '';
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
            $products .= wc_get_template_part( 'content', 'product' );
        endwhile;
    } else {
            $products = 'No products found';
    }
    echo $products;
    exit;

}

获得ajax结果后,您可以在前端(例如ajax)上替换产品的内容。

//on ajax success
....
$('.products').html(result); 

我希望这会有所帮助。