• Hi
    Not getting logged in user id in cronjob function.

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

    have tried two method:
    $user_id = get_current_user_id();
    $current_user = wp_get_current_user();
    $current_user->ID;

    but none of that works. I am logged in as subscriber role.

    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • There no user in cron jobs. Use WP_User_Query https://developer.www.ads-software.com/reference/classes/wp_user_query/

    Thread Starter Ahir Hemant

    (@hemant-ahir)

    Hi,

    Thnaks for your suggestion, but that is not what i want. I have created small plugin where i want to get logged in user ID and only logged in user can get something like emaail or other content that i want to send, but logged in user id(subscriber or any other roles) is alays return 0.

    That’s because there’s no user in cron jobs.

    You should create a recursive event like this:

    add_action( 'init', function () {
        $user_id = get_current_user_id();
        if ( ! $user_id ) return;
     
        $interval = 180;
        $last_time = get_user_meta( $user_id, 'isa_last_time', true );
    
        if ( ! $last_time || time() - $last_time >= $interval ) {
            // do something...
        }
    
        update_user_meta( $user_id, 'isa_last_time', time() );
    } );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘logged in user id not getting in wordpress cron job’ is closed to new replies.