Reputation: 455
Whenever I try to get current user id in wordpress cron job it returns 0. Is there any way to get current logged in user id in wordpress cron job.
here is sample code.
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
$schedules['every_three_minutes'] = array(
'interval' => 180,
'display' => __( 'Every 3 Minutes', 'textdomain' )
);
return $schedules;
}
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}
// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func');
function every_three_minutes_event_func() {
$user_id = get_current_user_id();
$user_points = get_user_meta( $user_id, 'remaing_points', true);
// send mail
//wp_mail();
}
Method #1
$user_id = get_current_user_id();
Method #2
$current_user = wp_get_current_user();
$current_user->ID;
I have tried these two method to get user id but no luck.
Upvotes: 0
Views: 880
Reputation: 11
You can set the user data in hook by $args.
$args = [ is_user_logged_in(), wp_get_current_user() ];
wp_schedule_event( $time, 'daily', 'close_session_daily_hook', $args );
In function
add_action( 'close_session_daily_hook', 'do_this_daily', 10, 2 );
function do_this_daily( $is_user_logged_in, $current_user ) {
// do some magic
}
Look more examples in https://developer.wordpress.org/reference/functions/wp_schedule_event/
Upvotes: 1
Reputation: 1314
If you are manually invoking the cron by running wp-cron.php, there is no user.
If you are relying on WordPress's cron to trigger on a user action request, you may get a non-zero user id if the user is logged in. If the user is a guest/non-logged in user, you will get a user id of 0.
Upvotes: 1