This PHP code for WooCommerce adds a custom field to the user profile page enabling the shop owner to allow specific shipping options for specific users. In this example, the code adds a checkbox and custom user role named VIP. If the customer uses the VIP role and the checkbox to allow local pickup is checked on the edit user profile screen, the local pickup option is displayed on the cart and checkout pages.
The code :
- Adds a checkbox for Local Pickup Settings to the edit user profile screen.
- Updates the checkbox option to store a value as true or false.
- Adds a custom user role named vip.
- Checks if the user has the VIP role and if the checkbox is checked.
- Displays the local pickup shipping option if both conditionals are true.
Copy and paste the PHP code to the end of your child themes functions file or custom functionality/code snippets plugin.
To configure the shipping settings in WooCommerce to work with the custom code provided in this download, follow these steps:
- Go to your WordPress admin dashboard.
- Navigate to “WooCommerce” and click on “Settings.”
- In the settings menu, click on the “Shipping” tab.
- Click on “Local Pickup” under the Shipping Zones and Methods section.
- Configure the “Local Pickup” settings according to your needs. Make sure it’s enabled and set up the shipping cost, if applicable. You can set the cost to zero if it’s free for users with the ‘vip’ role.
- Save your settings.
Here’s a summary of the 4 functions included in the code and how they work:
add_custom_field_for_admins: This function adds the “Local Pickup Settings” field to the user profile for administrators only. It checks if the current user has the ‘administrator’ role before displaying the field.
save_custom_field_data: This function saves the custom field data (local_pickup_allowed) when the user profile is updated. It also checks if the current user has the ‘administrator’ role before saving the data.
show_local_pickup_for_vip_users: This function conditionally shows the “Local Pickup” shipping method for users with the ‘VIP’ role and the ‘local_pickup_allowed’ custom field set to “Yes.” It filters the available shipping methods based on the user’s role and custom field.
add_vip_user_role: This function adds a custom user role named ‘VIP’ with customizable specific capabilities.
The code displays the “Local Pickup Settings” field for administrators and conditionally shows the “Local Pickup” shipping method for users with the ‘VIP’ user role when the custom field ‘local_pickup_allowed’ is set to “Yes.”