Recently I was working on a plugin where we wanted to use the media uploader of WordPress for our requirement. WordPress built a media uploader beautifully that allows a user to upload a new image or use an existing image from the media library. We wanted a custom image button to upload an image through the media uploader.
It is always recommended to use the built-in media uploader if you are looking for a custom solution to upload an image in the backend. By doing it you are following WordPress standards. Implementing a media uploader just takes a few lines of code. So without further discussion, let’s get started with it.
For this tutorial, I will add a custom image button for the post and page. With a click of this button, the media uploader will open where the user can upload the image or choose an existing image. The uploaded image URL would be set in a custom meta field and saved as a post meta for the specific post or page.
Add Custom Meta Box in WordPress
A Meta box is nothing but a block on a post or page. Categories, Tags, Featured Image, Excerpt, Discussion, etc are examples of meta boxes. Using the Meta box you can add additional information for the post and page.
We need a meta box that contains the upload image button and a text field. When a user clicks on the button, they will upload the image and the final image URL will be set in the text field.
Adding a meta box is easy and straightforward. Write the below code in the functions.php
file which will add a meta box for you.
function aw_custom_meta_boxes( $post_type, $post ) {
add_meta_box(
'aw-meta-box',
__( 'Custom Image' ),
'render_aw_meta_box',
array('post', 'page'), //post types here
'normal',
'high'
);
}
add_action( 'add_meta_boxes', 'aw_custom_meta_boxes', 10, 2 );
function render_aw_meta_box($post) {
$image = get_post_meta($post->ID, 'aw_custom_image', true);
?>
<table>
<tr>
<td><a href="#" class="aw_upload_image_button button button-secondary"><?php _e('Upload Image'); ?></a></td>
<td><input type="text" name="aw_custom_image" id="aw_custom_image" value="<?php echo $image; ?>" /></td>
</tr>
</table>
<?php
}
After adding the above code, go to the edit screen of your post or page and you should be able to see the new meta box along with their fields.
Customize WordPress Media Uploader
You are ready with your meta box. The next thing is on the click of the ‘Upload Image’ button, open the media uploader, and set the uploaded image URL in the text field. For this, you need to create a js file and enqueue it in a WordPress environment.
Let’s create a js awscript.js
and enqueue it as follows:
function aw_include_script() {
if ( ! did_action( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
wp_enqueue_script( 'awscript', get_stylesheet_directory_uri() . '/js/awscript.js', array('jquery'), null, false );
}
add_action( 'admin_enqueue_scripts', 'aw_include_script' );
Here, I have given the theme path assuming you are adding a whole code to the theme. If you are doing it through a plugin then you need to adjust the path.
To perform this task I have taken a reference of Javascript Reference/wp.media and written the jQuery code. In the awscript.js
we will write a media uploader code as follows.
jQuery(function($){
$('body').on('click', '.aw_upload_image_button', function(e){
e.preventDefault();
aw_uploader = wp.media({
title: 'Custom image',
button: {
text: 'Use this image'
},
multiple: false
}).on('select', function() {
var attachment = aw_uploader.state().get('selection').first().toJSON();
$('#aw_custom_image').val(attachment.url);
})
.open();
});
});
Now click on the ‘Upload Image’ button, it will open the media uploader. Choose or upload an image. This image URL will be added in the text field. Finally, I am going to save this URL in the postmeta
table with the key aw_custom_image
. Of course, you can give any name for the key.
function aw_save_postdata($post_id)
{
if (array_key_exists('aw_custom_image', $_POST)) {
update_post_meta(
$post_id,
'aw_custom_image',
$_POST['aw_custom_image']
);
}
}
add_action('save_post', 'aw_save_postdata');
The save_post
action triggered whenever a post or page is created or updated. Using this action you can inject your code into the system. You can read more about this hook on WordPress documentation.
I hope you got to know about adding a custom media uploader in WordPress. Give it a try let me know your thoughts in the comment section below.
Related Articles
- MailChimp Integration with Contact Form 7 Plugin
- How to Add Code After the Body Tag in WordPress
- How to Add Image Field to Taxonomy in WordPress
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
i did everything but when i click on button nothing happens.
Are there any errors in the browser console?
No erros on console. Just not opens.
When i click ok button nothing happens
i just copy and paste everything like the blog said, but nothing happens when i click the button.
I tried this. Everything works including the media uploader.
But when I publish the post, I don’t see any image that I have uploaded. How can I solve this?
To display it on front-end, fetch the image
$image = get_post_meta(POST_ID, ‘aw_custom_image’, true);
Please I will like to know if there is a way to add wordpress featured image default button on frontend post submission?
I think what you are looking for is to set the featured image programatically. Refer to this article and see if it helps https://artisansweb.net/set-featured-image-programmatically-wordpress/
I used those to show in front end ID, ‘aw_custom_image’,true);?>
but output shows only url
Wrap it inside img tag like
<img src='URL' />
Thank you so much for the code.
I have one question.
How to remove the uploaded image by pressing a button?
Did you check it by keeping the text field empty?
thank you very muchhhhh
sir how i can create image gallery using custom meta box for my custom plugin
First thanks for the code. I have a question about the media up-loader. It works and gives me the option of form file or media library, but no images are in the media library even though I have images in the library. How can I see the already uploaded images.
For me it worked out just by commenting this line (uploadedTo : wp.media.view.settings.post.id) on the script (if I’m not wrong, it filters the images shown to the ones uploaded to this post only):
[…]
aw_uploader = wp.media({
title: ‘Custom image’,
library : {
/*uploadedTo : wp.media.view.settings.post.id,*/
type : ‘image’
},
button: {
text: ‘Use this image’
},
multiple: false
}).on(‘select’, function() {
[…]
Hi!
I have used your code the image upload option is appeared but media uploader is not working.
Use JQuery code and then check
haha,it appeared,but click Use this image button,Added to the article…
i try add before .open(); like this “wp.media.editor.open();”
It appeared! thank you! 😀
hello,Sajid Sayyad
I use your code. I’m glad to be able to upload it,But how can it see other file types, as well as the files of the media library. Now can only see the file of the picture currently.I uploaded .text .JS…… There’s no way to see it again,Only after uploading can choose.
how to show img front end page