I created a new role called "Wholesaler". The role works as expected.
I also created a custom price field called "Wholesaler price". It also works as expected.
I check the user role, if they are assigned as a wholesaler, I give them the custom product price (if it is filled in). I have everything working except I can't figure out the final piece. How do I pull the current product ID, get the wholesale price, and assign it. My functions.php code is below:
/* 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 );
}
I can give the wholesaler a fixed percentage offer but that isn't my goal.