Adding Custom Image Button with Media Uploader in WordPress

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 in 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>