So I helped someone launch a site and they wanted a discounted product when someone purchased a specific product. I found a solution and implemented it and it worked at launch of the site and is no longer changing the role of customers when they purchase the products. I tried to get support from Woothemes and they don't support customization and want them to purchase a $129 extension to handle this.
Does anyone out there have a solution for this that still works?
Here is my code:
// Update User on purchase https://gist.github.com/troydean/9322593
function lgbk_add_member( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
}
if ( $order->user_id > 0 && $product_id == '247' || $order->user_id > 0 && $product_id == '255') {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'customer' );
// Add role
$user->add_role( 'author' );
}
}
add_action( 'woocommerce_order_status_completed', 'lgbk_add_member' );
UPDATE
Normally this updated code version should work with
woocommerce_order_status_completed
and then you should try this code before.(This code is also compatible with next upcoming major WooCommerce update 2.7).
Here is the code:
But as I don't know how your order is changed to
'completed'
status, if you want to be sure (in all possible cases) that the customer that will buy one of your 2 specific products, will have his role changed from'customer
' to'author'
when order status is set to'completed'
, I will recommend you trying to use this an email notification hook (if the first code snippet doesn't work).For example here I use
woocommerce_email_before_order_table
hook, that will be executed and fired on "Completed order customer email notification" with the help of some conditions.(This code is also compatible with next upcoming major WooCommerce update 2.7).
Here is your revisited and tested code:
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.