Answer the question
In order to leave comments, you need to log in
How do I change the user role at checkout and assign a subscription with PaidMemberships Pro?
Hello everyone, I have 3 hooks
1. Completes the payment through woocomerce
2. Changes the user role when the payment is completed
3. Does not work correctly, when changing the user role with the second hook, it does not assign a subscription level to it, help me fix it!
ps If you change the user role to customer in settings / users, then a subscription is assigned to him!
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) {
if ( ! $order_id ) {
return;
}
$order = wc_get_order( $order_id );
if( $order->has_status( 'processing' ) ) {
$order->update_status( 'completed' );
}
}
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 == '12429' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add role
$user->add_role( 'customer' );
}
}
add_action( 'woocommerce_order_status_completed', 'lgbk_add_member');
function assign_pmpro_level_to_role($user_id, $role, $old_roles)
{
global $current_user;
//checks if the user doesn't have a membership level yet
if(!$current_user->user_id) {
//we found a role related to pmpro level
if($role == "customer")
{
pmpro_changeMembershipLevel(6, $user_id); //gives default customers the level 20 free registration membership
}
}
}
add_action('set_user_role', 'assign_pmpro_level_to_role', 10, 3);
Answer the question
In order to leave comments, you need to log in
The set_user_role hook is not present in the add_role method, it is present in the set_role method;
you need it like this
function assign_pmpro_level_to_role($user_id, $role)
{
global $current_user;
//checks if the user doesn't have a membership level yet
if(!$current_user->user_id) {
//we found a role related to pmpro level
if($role == "customer")
{
pmpro_changeMembershipLevel(6, $user_id); //gives default customers the level 20 free registration membership
}
}
}
add_action('add_user_role', 'assign_pmpro_level_to_role', 10, 2);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question