根据Woocommerce

时间:2018-04-17 20:19:13

标签: php wordpress woocommerce advanced-custom-fields custom-taxonomy

如何修改WooCommerce的主循环以根据登录用户的ACF字段进行过滤?我使用ACF向用户配置文件添加了一个新字段,它从产品属性(Vehicle Year)中提取选择列表。我想做到这一点,所以产品只根据他们选择的车辆年份出现在用户身上。我无法弄清楚如何修改循环所以无论客户观看什么WooCommerce页面,它都会被过滤,只显示具有与其用户配置文件中选择的Vehicle Year相匹配的属性的产品。

我将以下代码添加到archive-products.php页面以检查登录用户。如果你有更好的主意,我就会开放。

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
    $user = new WP_User(get_current_user_id());
    $uid = $user->ID;
$year = get_field("vehicle-year", "user_$uid");
echo $year->name;
}

这有助于我确认我可以根据登录的用户获取ACF字段。

我知道我需要的东西有这样的东西,我只是不确定如何让它替换/附加到主要的WooCommerce循环,所以它总是过滤产品。

'tax_query' => array(
        'relation'=>'AND',
        array(
            'taxonomy' => 'pa_year-2',
            'field' => 'name',
            'terms' => '1970'
        )
    )

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

使用这个专用的WooCommerce钩子尝试以下内容:

add_filter('woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 20, 2 );
function custom_product_query_tax_query( $tax_query, $query ) {
    // Only on front end for logged in users
    if( is_admin() || ! is_user_logged_in() ) return $tax_query;

    // HERE get and Define the product attribute term name (from user data) to be used
    $term  = get_field( "vehicle-year", 'user_' . get_current_user_id() ); // Get the year (term)
    $terms = array( $term->name );

    // The taxonomy for your product attribute
    $taxonomy = 'pa_year-2';

    $tax_query['relation'] = 'AND'; // Not really necessary as it's defined by default
    $tax_query[] = array(
        'taxonomy' => $taxonomy,
        'field'    => 'name', // 'term_id', 'slug' or 'name'
        'terms'    => $terms,
    );

    return $tax_query;
}

代码进入活动子主题(或活动主题)的function.php文件。它应该有效。