doukuangxiu1621 2018-04-17 20:19
浏览 108
已采纳

根据Woocommerce中的用户动态产品属性值过滤产品循环

How do I modify the main loop of WooCommerce to filter based on a logged in user's ACF field? I have added a new field to the user profile using ACF, it pulls a select list from a product attribute (Vehicle Year). I want to make it so products only show up for the user based on what vehicle year they've chosen. I can't figure out how to modify the loop so no matter what WooCommerce page the customer views it will be filtered to only show products with the attribute that matches the Vehicle Year selected in their user profile.

I added the following code to the archive-products.php page to check for the logged in user. If you have a better idea, I'm open.

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

This helped me confirm I can get the ACF field based on the user logged in.

I know I need something that has something like this, I'm just not sure how to make it replace/attach to the main WooCommerce loop so it's always filtering the products.

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

Appreciate any help you can offer.

  • 写回答

1条回答 默认 最新

  • duanhao8540 2018-04-17 20:44
    关注

    Try the following with this dedicated WooCommerce hook:

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

    Code goes in function.php file of your active child theme (or active theme). It should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多