K
K
Kirill Makarov2018-02-20 16:48:53
WordPress
Kirill Makarov, 2018-02-20 16:48:53

Automatic change of user roles in Wordpress after payment in Woocommerce?

Hello everyone, the task is as follows: It is
necessary that after paying through the Yandex Money gateway, the user's role, let's say from the subscriber, changes to the role set by me. Among the plugins, I did not find free ones, but I read that in the code this can be done on the same site. Could you explain in more detail how through the console and in what documents (I understand they are also called hashes) you can enter such functions.
Interested in payment from Yandex and the transfer of the client from the old to the new role.
(Translation is necessary for the user to obtain information from pages with restricted access).
If I was inaccurate somewhere, please forgive me, because by education I am an engineer and not a programmer.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
petrmish, 2020-04-15
@kirbi1996

add_action('woocommerce_thankyou', 'change_user_role_on_order_success');
function change_user_role_on_order_success($order_id ) {
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
$wp_user_object = new WP_User($user_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 ( $product_id == '999' && $wp_user_object->roles[0] != "administrator"){ // Не исправлять админа!
wp_update_user( array( 'ID' => $wp_user_object->ID, 'role' => "my-role" ) );
} else
if ( $product_id == '777' && $wp_user_object->roles[0] != "administrator"){ // Не исправлять админа!
wp_update_user( array( 'ID' => $wp_user_object->ID, 'role' => "my-role2" ) );
}
}

As you can see in the code, users will get my-role if they buy product id 999, and they will get user role my-role2 when they buy product id 777. Replace with the one you want. This code works for me. Place in function.php of your theme.

O
Orkhan Hasanli, 2018-02-20
@azerphoenix

Hello, I would recommend that you contact a freelance exchange and set the task of implementing such functionality.
And so a quick google search gave the following results (without owning PHP, the WP code and the Woocommerce API, you are unlikely to be able to implement this):
- https://nicola.blog/2016/03/07/changing-user-role-. .. (must be pasted in functions.php)
- https://gist.github.com/troydean/9322593
- https://wordpress.stackexchange.com/questions/1206...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question