I am working on uploading an image to the media library and then attaching it to the featured image. I put the code below in my functions.php file and submitted a JSON file through postman, but for some reason it uploaded thousands of times until i had to kill the process and remove the code to get it to stop. It is uploading to the media library but keeps creating images. I have no loop in my code. I was just testing the code below to see if i could get it to run once. I am still learning how Wordpress works. Sorry if these are dumb questions.
- Does functions.php continuously execute while Wordpress is running?
- Should this be in functions.php file and how do i get it to execute only once?
$url = 'http://localhost/download.png';
$request = wp_remote_post(
'http://localhost/wordpress/wp-json/wp/v2/media',
array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'api-user:xxxx xxxx xxxx xxxx xxxx xxxx' ),
'Content-Disposition' => 'attachment; filename="' . basename( $url ) . '"',
'Content-Type: ' . wp_get_image_mime( $url ),
),
'body' => file_get_contents( $url )
)
);
if( 'Created' === wp_remote_retrieve_response_message( $request ) ) {
$body = json_decode( wp_remote_retrieve_body( $request ) );
$featured_image_id = $body->id;
}