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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失