- Does functions.php continuously execute while WordPress is running?
Yes, it’s run on each page load. You can learn more about the (theme) functions file at https://developer.wordpress.org/themes/basics/theme-functions/.
- Should this be in functions.php file and how do i get it to execute only once?
It can be put in that file, however, it should be run conditionally, e.g. put it in a function and then call the function from within your template file, or from within a hook. That’s how you can get it to execute only once. (but whether it’s actually going to be executed only once, depends on your code)
Example:
-
Code in the active theme’s
functions.php
file:<?php /** * Your Theme functions and definitions * * @link https://developer.wordpress.org/themes/basics/theme-functions/ */ function my_upload_image_function() { // your code here which uploads the image }
-
Then in your template file, just call the function when necessary:
my_upload_image_function()
. -
Or you can hook the function on a specific action:
add_action( 'hook_name', 'my_upload_image_function' );
So that’s a brief info about the theme functions file, and now, this is about what your code is trying to do.
- I see you’re making a remote POST request to the
/wp/v2/media
endpoint, but actually, you could instead userest_do_request
to make API requests internally, or use a WordPress-specific function for uploading files likemedia_sideload_image()
which fetches a remote image and adds it to the WordPress media library.