Igor Simic
5 years ago

Select image or video by using Wordpress media library - JavaScript


How to choose specific image type or video from Wordpress media library by using Angular JavaScript? To achieve this we have to use wordpress media frames: wp.media.frames, which will help us to select or upload image/media to the wordpress library.

To use media frames we have to include it, go to your wordpress functions.php file and add this:
if(function_exists( 'wp_enqueue_media' )){
            wp_enqueue_media();
        }
Now we can use it in our code. So let's say this is gong to be triggered on a button click by calling function selectImage():
<md-button class="md-mini" ng-click="selectImage()" aria-label="Select
 icon" md-no-ink="true" md-ripple-size="full">Select image</md-button>
Just for fun let's create selected image preview:
<img id="imgPrev" ng-src="{{imagePreview}}" > 
OK, now let's go to our controller and add this function  to select ONLY png images from WP media  frame:
app.controller('ThemeOptionsCtrl',['$scope','resContent','$rootScope',function($scope,resContent,$rootScope){
    
     // set the default URL for image preview. resContent => resolveContent (data from route resolve, but it could be any data with valid img URL)
     $scope.imagePreview = $scope.resContent.img[0].src;
     
     // this function will be called after image is selected in wp media frame
     $rootScope.updateImageURL = function(url,ID){

		$scope.imagePreview = url;
		$scope.imageID = ID; // can be usefull
	}

    // let's create function
    $scope.selectImage = function(){
 
		// If the media frame already exists, reopen it.
		    if ( frame ) {
		        frame.open();
		        return;
		    }

		    
     	// Create the media frame.
		    var frame = wp.media.frames.items = wp.media({
		        title: 'Select PNG image', // media window title
		        library: {type: 'image/png'}, //select ONLY png image, it could be image/jpeg or image/jpg for images or 'video/MP4'
		        
		        /* or combination of media types
		        
			        library: {
				            type: [ 'video', 'image' ]
				    },
			    */
			   
		        multiple: false,
		        button: {text: 'Insert'}
		    });

		    frame.on(
				'select',
				function() {
					var attachment = frame.state().get( 'selection' ).first();
 					
 					// let's output different data for selected image or video
					console.log("attachments");
					console.log(attachment);
					console.log(attachment.attributes.url);
					console.log(attachment.attributes.orientation);
					console.log(attachment.attributes.sizes);
					console.log(attachment.id);

					// lets call rootscope function to update image src
 					$rootScope.updateImageURL(attachment.attributes.url,attachment.attributes.id);
 					//$("#iconImg").attr('src',attachment.attributes.url);
 					
				}
			);
 

		    // Finally, open the modal.
		    frame.open();


	}
}]);

There you have it.
Happy coding, mofo!