Answer the question
In order to leave comments, you need to log in
WP scheduled function changes WooCommerce User Role after paying monthly or yearly subscription... How to improve PHP's change_role function?
Hello! How to modify the WP PHP function to automatically change roles by subscribing to the WordPress CMS.
There is a feature that changes the role after paying for a specific WooCommerce product.
add_action( 'woocommerce_order_status_completed', 'change_role_on_vip' );
function change_role_on_vip( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
$products_to_check = array( '3420' ); // id товара WooCommerce
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
$user = new WP_User( $order->user_id );
// заменить роль
$user->remove_role( 'lead' );
$user->add_role( 'vip' );
// окончание цикла
break;
}
}
}
if ( ! wp_next_scheduled( 'alter_user_role_hook' ) ) {
wp_schedule_event( strtotime('tomorrow'), 'daily', 'alter_user_role_hook' );
}
function alter_user_role_function() {
global $wpdb;
$today = date('Y-m-d H:i:s',strtotime('today'));
$expired = $wdpb->get_col("SELECT user_id FROM {$wpdb->usermeta} WHERE expired_key < {$today}");
if (!empty($expired)) {
foreach ($expired as $uid) {
wp_update_user(
array (
'ID' => $uid,
'role' => 'havent_paid'
)
);
}
}
}
add_action( 'alter_user_role_hook', 'alter_user_role_function' );
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question