• Hello, I need help to understand how to actually execute PHP code on WordPress, because I feel like I’m doing something wrong. So, what I tried is to write (actually, modify from an online example) some PHP code to update my WooCommerce products stock based on data from a CSV that sits in the “wp-content/upload” folder, following this guide:

    https://rudrastyh.com/woocommerce/update-product-stock-from-csv.html

    My code is for now equal to this one, I just changed the name of the file to test it and added <?php at the start of the file. The file with this PHP code is in the root, and I put the code to schedule the execution in functions.php. The question is, it doesn’t seem to work. If I go and see from the plugin Query Monitor, I can’t see it running. Same if I check processes running from my host command line. And also WP Activity Logs, another plugin, doesn’t notify stocks actually changing. It doesn’t seem the script is going at all, what am I missing? The code seems right, and also using WP-CLI to start the script doesn’t seem to work. Same if I open it going to mywebsite.com/myfile.php, I just get a blank page. I ran out of options, could someone clarify? Thank you in advance.

    The page I need help with: [log in to see the link]

Viewing 4 replies - 1 through 4 (of 4 total)
  • WPMajestic

    (@wpmajestic)

    Hello @lucas6888,

    Why you did not add the both code snippets to the functions.php file of your theme?

    Or, if you are not using a child theme, you can use the Code Snippet plugin to add those two functions. It should work that way.

    Kind regards.

    Thread Starter lucas6888

    (@lucas6888)

    Hello, I tried inserting the script as a snippet using a plugin but it didn’t work. I now solved by creating a custom plugin. I didn’t put it in functions.php because I assume that if I did, the code would be executed at each site load, and I don’t want that. Is this right?

    Moderator bcworkz

    (@bcworkz)

    Yes, code in functions.php runs on every page load. But so does plugin code. To limit execution, we use action hooks to only execute when the action fires. Some fire multiple times, others only fire with certain requests. There are ways to define our own action hooks so they only fire when we want. One way is to use wp_schedule_event(). This sets up a recurring wp-cron event, which requires some sort of HTTPS request to happen before any wp-cron events are triggered. This usually not an issue unless you have a very infrequently visited site. You can instead schedule server Cron jobs to run code as needed. This is more reliable but is not always accessible to some WP site admins.

    Thread Starter lucas6888

    (@lucas6888)

    I have a more clear overview now, thank you for your explanation.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.