0

So I have this block of code and it is driving me crazy:

    if ( ! wp_next_scheduled( 'change_quote_hook_short' ) ) {
    wp_schedule_event( time(), 'one_minute', 'change_quote_hook_short' );
}

add_action( 'change_quote_hook_short', 'get_next' );

function get_next() {

$new_ar = array ('Ad1', 'Ad2', 'Ad3', 'Ad4', 'Ad5');

$id = ++$_SESSION['ad_id'] % count($new_ar);
$_SESSION['ad_id'] = $id;

$rsmid_single = $new_ar[$id];

update_option('rsmid_single', $rsmid_single);

}

On each run of the function get_next, when I check $rsmid_single variable it changes value correctly. Still, the option in the table is always set at Ad2. I have also checked, cron is working (when I switch value for $rsmid_single, it shows in the table after one minute). Like update_option is executed before increment finished. If you can please tell me if this is possible or should I search for some alternative approach?

  • If it's always being set to Ad2, and this is in position 1 in the array, it suggests that when you're first referring to $_SESSION['ad_id'] it's coming back as Zero every time. Likely meaning it's not be set/updated correctly when you are calling $_SESSION['ad_id'] = $id;. Therefore, I wonder if you're using sessions correctly and calling session_start(); Note that WordPress does not use Sessions in the manner you're using, so you should be handling that so you can use $_SESSION as you are intending... – Paul G. Jun 1 at 15:02
  • Thank you Paul for taking your time and checking this. I am using session_start(); at the top, just didn't copy that line. I have tried with cookies, same result. The issue is between $rsmid_single and update_option. $rsmid_single is changing values on each iteration when I check, so that part should be working correctly. The issue is that update_option is not receiving it... – Milos Jun 2 at 18:33
  • I'm really not sure I understand. At no point in this code are you using get_option('rsmid_single') so how do you know it's not being set? You're actually setting a value in the $_SESSION and using this instead, not the WP option. I think you're getting confused on what should store what. As I mentioned, you get Ad2 because session ad_id always returns zero - have you verified that session is updated correctly? Why use session? Why not use the WP options or even the transients? You're jumping from sessions to wp options, but then you're not using the wp option. – Paul G. Jun 3 at 8:37
  • Thank you, Paul. You are right, the session is not the way to go here. I have switched to transients, and finally, have this working. Your feedback really helped. Cheers! – Milos Jun 3 at 12:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.