A
A
Alexey Gorbunov2020-01-26 15:09:48
WordPress
Alexey Gorbunov, 2020-01-26 15:09:48

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;
     }
    }
}


How to add a PHP function with a condition: payment by subscription.

For example, he paid on the 15th of the current month and he gets the vip role for a month or a year, depending on the product id .

After the time has elapsed, it automatically resets to the role: lead.

The period of time is not set by a number (30 days, 365 days), but by the date of payment and the subscription must be extended from date to date. For example, both in February (28 days) and in May (31 days) the 15th is the same.

Condition: the subscription must be renewed on the day of the current payment. That is, the term expired on the 15th, hung in the role: lead and extended on the 25th. A new cycle began from the 25th to the 25th.

* * *

Hint(found online).

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' );


* * *

How to link two proposed codes into one? Or create and modify any of them.

* * *

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question