1

I have various processing scripts I want to run that modify WooCommerce order data. Currently, I build the scripts as a function in my theme's functions.php and then attach the function to a shortcode. I then build a page in Wordpress that just contains that shortcode and load the page in my browser to execute the script.

That seems incredibly convoluted and there has to be a "proper" way to do this that doesn't involve creating pages and running things through the theme.

I need access to things like WP_Query and the WooCommerce Order class, but essentially would like to have the full Wordpress and WooCommerce classes/functions available to me, just like they are when I run things through pages/shortcodes.

Is there a proper way to easily bootstrap all the Wordpress includes, without having to go all the way through the theme?

3

Is there a proper way to easily bootstrap all the Wordpress includes, without having to go all the way through the theme?

That's the wrong question. Shortcodes are far from the only way to run code from a theme or plugin. You've correctly identified them as inappropriate for the job though. What I think you should be looking to do is to find a better way to run your scripts from a theme or plugin.

The way I see it, you have 2 main options, basically depending on how your want your script to be triggered.

If you want to manually trigger the script, then you should create a page in the admin with a button that triggers the script. The basic steps for that would be:

  1. Use add_menu_page() to add the page to the admin somewhere.
  2. For the contents of the page output a form with the action set to <?php echo esc_url( admin_url( 'admin-post.php' ) ); ?> and a hidden input with the name"action" and value as a unique identifier for your functionality.
  3. Add a hook to admin_post_{whatever your action name is} that runs your script.

This tutorial on admin forms covers the topic in more detail.

Now you'll have a place in the admin where you can go and push a button to run your scripts.

If you want to automatically trigger the scripts on a schedule, then you should use WP Cron to schedule the script function to run. The documentation for that is here, but essentially rather than adding your script function to a shortcode with add_shortcode(), add the function to a hook with add_action(), then use wp_schedule_event() to schedule the action to run at certain times.

You can use wp_next_scheduled() to automatically schedule the script to run again after each time it runs:

if ( ! wp_next_scheduled( '{whatever your hook name is}' ) ) {
    wp_schedule_event( time(), 'hourly', '{whatever your hook name is}', $args );
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.