1

I need to set up a cron to change role of a user at a specific time. For example- At 8 PM everyday, the role of a specific user should be changed from "Customer" to "Editor"

How to accomplish this in wordpress?

UPDATE:

I have scheduled the function as follows but it's not running at the time set:

if( !wp_next_scheduled( 'import_into_db' ) ) {

    wp_schedule_event( strtotime('12:04:00'), 'daily', 'import_into_db' );

    function import_into_db(){

        $u = new WP_User(3);

        $u->set_role('editor');

    }

    add_action('wp', 'import_into_db');
} 

The functions is running fine independently (without scheduling) but doesn't run when scheduled. Cron is working fine on my install and time is set as per UTC. What's wrong in the scheduling part of my code?

2 Answers 2

2

You can do something like this

add_action("after_switch_theme", "schedule_cron_job"); // hook the schedule on theme switch or plugin activation based on the your usage also switch your theme after putting this on functions.php
function schedule_cron_job(){

    if (! wp_next_scheduled ( 'import_into_db' )) {

        wp_schedule_event(strtotime('12:04:00'), 'daily', 'import_into_db');

    }

}

add_action('import_into_db', 'your_cron_job'); // You were hooking to wp


function your_cron_job(){

    $u = new WP_User(3);
    $u->set_role('editor');

}

You can use cron manager plugins to check if cron job is scheduled or not.

5
  • Hi, I need the function to be active at all times in my website theme's function file, hence don't require to hook it to theme/plugin activation. How to modify your code to achieve this?
    – dc09
    Commented May 3, 2018 at 11:25
  • once theme is switched the schedule will continue daily no need to worry. You can use without any change. Commented May 3, 2018 at 11:26
  • If you removed the cron via cron manager, you can simply switch theme to activate again. Commented May 3, 2018 at 11:29
  • Can we hook the schedule on something else that's more reliable as the schedule might not run if no theme is switched?
    – dc09
    Commented May 3, 2018 at 13:29
  • I used this function, the cron has been set up to run daily as per cron manager but the time is fixed at 9:50 PM no matter what I change it to in the code. Basically, cron is working but not at the designated time.
    – dc09
    Commented May 4, 2018 at 6:25
0

You need to get the user's ID, create a WP_User instance, and with that, you can change the role for a specific user:

$u = new WP_User(3);
$u->set_role('editor');

You can then use a custom interval to schedule this. How to do that has been answered here: Schedule event at specific time every day

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.