Run a wordpress query every week

2019-07-23 08:55发布

Good morning everyone. As the title say I'm trying to find a way to run a wordpress query every week to update a section in my site with the suggested posts of the week.

Looking around I've found the wp_cron feature, and it seems like the thing I'm looking for since I can't set up a cron job on the server. The problem is that I wasn't able to make it work. I've created this try-function in my functions.php

add_action( 'cron_hook', 'cron_exec' );

if( !wp_next_scheduled( 'cron_hook' ) ) {
   wp_schedule_event( time(), 'daily', 'cron_hook' );
}

function cron_exec() {
  echo time();
}

And i call the action in my post page with the following code:

do_action('cron_hook');

This is my first attempt at wp_cron so maybe I missed something but I was expecting to get the same time() everytime I refresh the page since the function should be fired once a day, but I ended up having the current timestamp on every refresh.

I'd like to know if I'm using correctly the wp_cron function and if it's the right thing to use in this case or there are bettere methods to achieve this result.

Thank you for the help and have a nice day.

1条回答
太酷不给撩
2楼-- · 2019-07-23 09:42

To execute cron every week you'll need something like this:

function custom_time_cron( $schedules ) {

    $schedules['every_week'] = array(
            'interval'  => 604800, //604800 seconds in 1 week
            'display'   => esc_html__( 'Every Week', 'textdomain' )
    );

    return $schedules;
}
add_filter( 'cron_schedules', 'custom_time_cron' );

add_action( 'my_cron_hook', 'my_cron_function' );

if (!function_exists('mytheme_my_activation')) {
    function mytheme_my_activation() {
        if (!wp_next_scheduled('my_cron_hook')) {
            wp_schedule_event( time(), 'every_week', 'my_cron_hook' );
        }
    }
}

add_action('wp', 'mytheme_my_activation');

if (!function_exists('my_cron_function')) {
    function my_cron_function() {
        echo time();
    }
}

The first function creates a new schedule - because you only have houly, daily and twicedaily as a reccurance.

Then you set up your scheduler. You check if there is a scheduled event with !wp_next_scheduled, and if it's not, you schedule the event

wp_schedule_event( time(), 'every_week', 'my_cron_hook' );

If you've already initialized a cron with a certain name, for it to get rescheduled you'll need to wp_clear_scheduled_hook.

Hope this helps :)

查看更多
登录 后发表回答