User Profile Discount Field and Application

The PHP code provides functionality for adding a custom discount field to WordPress user profiles and applying the selected discount rate to WooCommerce product prices. It hooks into user profile display and save actions, as well as WooCommerce product price filters.

<?php /** * Adds a custom field (dropdown) for discounts in user profiles. */ function cwpai_add_user_discount_field($user) { // Check if $user is an object before trying to access its properties $user_id = is_object($user) ? $user->ID : get_current_user_id(); // Get the current selected value $selected = get_user_meta($user_id, 'cwpai_user_discount', true); echo '<h3>' . __('Discount Settings', 'codewp') . '</h3>'; echo '<table class="form-table"><tr>'; echo '<th><label for="cwpai_user_discount">' . __('Discount Rate', 'codewp') . '</label></th>'; echo '<td>'; echo '<select id="cwpai_user_discount" name="cwpai_user_discount" class="regular-text">'; // Define discount options $discounts = array('40%', '30%', '20%', '10%'); foreach ($discounts as $discount) { echo '<option value="' . esc_attr($discount) . '"' . selected($selected, $discount, false) . '>' . esc_html($discount) . '</option>'; } echo '</select>'; echo '</td></tr></table>'; } add_action('show_user_profile', 'cwpai_add_user_discount_field'); add_action('edit_user_profile', 'cwpai_add_user_discount_field'); add_action('woocommerce_edit_account_form', 'cwpai_add_user_discount_field'); /** * Saves the selected discount rate when the profile is updated. */ function cwpai_save_user_discount_field($user_id) { if (!current_user_can('edit_user', $user_id)) { return false; } update_user_meta($user_id, 'cwpai_user_discount', $_POST['cwpai_user_discount']); return true; } add_action('personal_options_update', 'cwpai_save_user_discount_field'); add_action('edit_user_profile_update', 'cwpai_save_user_discount_field'); add_action('woocommerce_save_account_details', 'cwpai_save_user_discount_field'); /** * Applies the selected discount for the user viewing WooCommerce products. */ function cwpai_apply_user_discount_to_products($price, $product) { $user_id = get_current_user_id(); $user_discount = get_user_meta($user_id, 'cwpai_user_discount', true); if (!empty($user_discount)) { $discount_decimal = rtrim($user_discount, '%') / 100; $price -= ($price * $discount_decimal); } return $price; } add_filter('woocommerce_product_get_price', 'cwpai_apply_user_discount_to_products', 10, 2); add_filter('woocommerce_product_variation_get_price', 'cwpai_apply_user_discount_to_products', 10, 2);

Frequently Asked Questions

The code adds a custom field to user profiles for selecting a discount rate, and applies that discount to WooCommerce products.

Related public snippets