Search code examples
phpwordpresscron

What's the right hook for wordpress to execute an external cron job?


The thing with wordpress cron as I understand it will execute when someone visits the site, but I dont like it because it will slow pages when it happens.

Instead I want to add a cron job in my cpanel to run a php script, which should activate the hook I add with my custom plugin.

I tried to use ajax hook for admin-ajax.php, because it's the only one I know, which worked when I open URL but doesn't seem to work when I run the php script directly.


Solution

  • Solved in a weird way:

    /opt/php56/bin/php-cgi /XXXXXX/wp-admin/admin-ajax-XXX.php
    

    Calling a cron job like this is equivalent to a web request, the only thing missing now is the querystring, that's why I created the XXX file where I simply override my GET variable.

    $_GET['action'] = 'my_wp_ajax_action_hook';
    include './admin-ajax.php';
    

    I know it's different but it works so who cares, and I have a perk of being able to call it anytime I will by following the web address as well:

    /XXXXXX/wp-admin/admin-ajax-XXX.php or 
    /XXXXXX/wp-admin/admin-ajax.php?action=my_wp_ajax_action_hook
    

    Of course spammers should not know this url, otherwise you are going to get rekt. And just for the reference here is my wp hook function:

    add_action('wp_ajax_my_wp_ajax_action_hook', 'my_wp_ajax_action_hook');
    add_action('wp_ajax_nopriv_my_wp_ajax_action_hook', 'my_wp_ajax_action_hook');
    function my_wp_ajax_action_hook() {
        //you getting rekt here :-)
    }