Software Developer

Upload Images To Media Library From Your Theme in WordPress

This lets you upload images from a theme or plugin right into the WordPress Media Library. This leaves the images unattached to any post. They will simply be sitting in the Media Library ready for use.

If you want to attach the image to a post, or to set it as the featured image, see this instead.

Another term for this is to “sideload” an image into WordPress.

You don’t want to repeatedly upload the same image over and over agin, so hook it to your theme or plugin activation. This way it will only upload images once, upon activation. This example is for use within a theme so it’s hooked to “after_switch_theme”.

This example uploads 3 images from the theme’s “images” directory. Change the first parameter to show the path and filename of your own images. The second parameter (“0”) ensures that the images will not be attached to any post, but rather will just sit in the Media Library.

function my_theme_activation() {

	function my_sideload_image() {
		$img1 = media_sideload_image( get_template_directory_uri() . '/images/img1.png', 0 );
		$img2 = media_sideload_image( get_template_directory_uri() . '/images/img2.png', 0 );
		$img3 = media_sideload_image( get_template_directory_uri() . '/images/img3.png', 0 );
		
		
	}
	add_action( 'admin_init', 'my_sideload_image' );

}
add_action('after_switch_theme', 'my_theme_activation');

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]