将自定义字段价格作为产品价格分配给WooCommerce中的特定用户角色。

问题描述 投票:2回答:1

我创建了一个名为 "批发商 "的新角色。该角色按预期工作。

我还创建了一个名为 "批发商价格 "的自定义价格字段。它也按预期工作。

我检查用户角色,如果他们被分配为批发商,我给他们自定义产品价格(如果它被填写)。我有一切工作,除了我不能找出最后一块。我如何提取当前的产品ID,获得批发价格,并分配它。我的function.php代码如下。

/* Custom user roles */
add_role( 'wholesaler', 'Wholesaler', get_role( 'customer' )->capabilities );

add_action( 'woocommerce_product_options_pricing', 'action_woocommerce_product_options_pricing', 10, 0 );

/* Add custom wholesaler price field to general page */
function action_woocommerce_product_options_pricing() { 
    woocommerce_wp_text_input( array(
        'id' => 'wholesaler_price', 
        'class' => 'wc_input_price short', 
        'label' => __( 'Wholesaler price', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')',
    ) );
}

// Save Fields
function action_woocommerce_admin_process_product_object( $product ) {
    if( isset($_POST['wholesaler_price']) ) {
        $product->update_meta_data( 'wholesaler_price', sanitize_text_field( $_POST[ 'wholesaler_price'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

/* Custom prices by user role */
add_filter('woocommerce_get_price', 'custom_price_assign', 10, 2);

function custom_price_assign($price, $product) {
    if (!is_user_logged_in()) return $price;

        // Check if the user has a role of wholesaler
        if (check_user_role('wholesaler')){
            $price = $price; // Assign wholesale price for product (if it is set for that product)
        }

    return $price;
}

/* Check user role */
function check_user_role($role = '',$user_id = null){
    if ( is_numeric( $user_id ) )
        $user = get_user_by( 'id',$user_id );
    else
        $user = wp_get_current_user();

    if ( empty( $user ) )
        return false;

    return in_array( $role, (array) $user->roles );
}

我可以给批发商一个固定的百分比报价 但这不是我的目标。

php wordpress woocommerce hook-woocommerce price
1个回答
2
投票

你不需要你的功能 check_user_role() 因为你可以以同样的方式使用WordPress current_user_can().

也是钩子 woocommerce_get_price 自WooCommerce 3以来已被废弃。

要获得您的自定义批发商价格,您只需使用元键。wholesaler_price 喜欢。

1)与 get_meta() 的方法 WC_Product 对象 (自WooCommerce 3):

$price = (float) $product->get_meta( 'wholesaler_price' );

2) 或产品ID在 get_post_meta() 功能 (WordPress的老办法):

$price = (float) get_post_meta( $product->get_id()  'wholesaler_price', true );

现在在你的相关钩子代码函数中。

/* Custom prices by user role */
add_filter('woocommerce_product_get_price', 'custom_price_assign', 10, 2);
add_filter('woocommerce_product_variation_get_price', 'custom_price_assign', 10, 2); // For product variations (optional)

function custom_price_assign( $price, $product ) {
    // Check if the user has a role of wholesaler
    if ( current_user_can('wholesaler') && $wholesaler_price = $product->get_meta('wholesaler_price') ){
        return $wholesaler_price;
    }
    return $price;
}

代码进入你的活动子主题(或活动主题)的functions.php文件。经过测试,工作。

© www.soinside.com 2019 - 2024. All rights reserved.