WordPress Cron Schedule the if and else statement

The question:

I have a custom php loop/function written that works in the following way

$start = strtotime(date("Y-m-d H:i:s", strtotime("+5 hours")));
$end = get_post_meta( $post->ID, '_limited_dates_to', true );
$remaining = $end - $start; 
if ($end > $start) {
    wp_set_post_terms( $post->ID, 'not active', 'product_tag', false );
} else {
    wp_set_post_terms( $post->ID, 'active', 'product_tag', false );

Currently the loop works fine but it is attached with a timer as one can see easily in $start and $end.
Now what I am trying to get here is something of a product expiry thing going on. I need the cron to work this if & else loop and automatically set the active or not active tags.

How can this be achieved?
Currently I have to manually refresh the page so that the loop runs.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

wp_cron is a PHP level system and so also only runs on page load. It does not run on clock time so you’d still need to reload the page to get the loop to run.

Second, to get this working with wp_cron you’d need to pull all of your posts with _limited_dates_to set and loop through them. You’d need to do that every time the wp_cron job runs. That is likely to be a lot of server load as I doubt your expiration times fall into neat blocks that allow you to run a wp_cron job every few hours.

As is, you can check one post at a time as needed. That, I would argue, is the better way of doing this than using wp_cron.

Even if you have server access that allows you to set up a real system cron job you still have the same problem with needing to Loop through all posts with _limited_dates_to set.

Unless you have a very convincing reason that this needs to use wp_cron or cron, and it works as is, I’d say “leave it alone”. I don’t see the benefits and I do see potential drawbacks.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment