Changing user role after subscription is found


Im using Opal Membership plugin for real estate website.
The problem is that it’s only working for properties and i want to restrict other content as well (like pages, posts etc.)
I want to use Restrict User Access plugin for that but have to modify function.php to automatically change user roles after subscription is found.

The hook im using to check if user has valid membership is


I trying to modify the code below, to change user role from the default one to custom one, when membership is valid

 add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function wpglorify_change_role_on_purchase( $order_id ) {

// get order object and items
    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    $product_id = 56; // that's a specific product ID

    foreach ( $items as $item ) {

        if( $product_id == $item['product_id'] && $order->user_id ) {
            $user = new WP_User( $order->user_id );

            // Remove old role
            $user->remove_role( 'customer' ); 

            // Add new role
            $user->add_role( 'editor' );

It is for woocommerce to change role after purchase so it’s quite similar to what im trying to achieve.
Can someone guide me on how to achieve this?

Darek 2 years 2020-10-26T00:10:20-05:00 0 Answers 13 views 0

Leave an answer