How to Create Custom Meta Box For Multiple Images in WordPress

How to Create Custom Meta Box For Multiple Images in WordPress
219 Views

Hi, here I implement multiple image upload custom fields (WordPress custom meta box image upload) to page post type if you want it for another post type just change the post type name.

Add the following code to your current themes functions.php file. Go to your pages from WordPress admin and check that the multiple image upload custom field is added to each page.

<?php
add_action( 'add_meta_boxes', 'cxc_media_uploader_meta_box' );
function cxc_media_uploader_meta_box() {
	add_meta_box( 'cxc-media-field', 'Media Field', 'cxc_media_uploader_meta_box_func', 'page', 'normal', 'high' );
}
?>
  • The code starts by defines an action hook, add_action( ‘add_meta_boxes’, ‘cxc_media_uploader_meta_box’ )
  • The next step defines a function called cxc_media_uploader_meta_box.
  •  This is the name of the function that will be used to create and manage this meta box.
  •  The next line creates a new meta box with the name cxc-media-field and assigns it to post type (the default).
<?php 
function cxc_media_uploader_meta_box_func( $post ) {

	$banner_img = get_post_meta( $post->ID, 'cxc_post_banner_img', true );
	?>
	<table cellspacing="10" cellpadding="10">
		<tr>
			<td>Banner Image</td>
			<td>
				<?php echo cxc_multi_media_uploader_field( 'cxc_post_banner_img', $banner_img ); ?>
			</td>
		</tr>
	</table>
	<?php

}
function cxc_multi_media_uploader_field( $name, $value = '' ) {

	$image = '">Add Media';
	$image_str = '';
	$image_size = 'full';
	$display = 'none';
	$value = explode( ',', $value );

	if ( !empty( $value ) ) {
		foreach ( $value as $values ) {
			if ( $image_attributes = wp_get_attachment_image_src( $values, $image_size ) ) {
				$image_str .= '<li data-attechment-id=' . $values . '><a href="' . $image_attributes[0] . '" target="_blank"><img src="' . $image_attributes[0] . '" /></a><i class="dashicons dashicons-no delete-img"></i></li>';
			}
		}
	}

	if($image_str){
		$display = 'inline-block';
	}
	return '<div class="cxc-multi-upload-medias"><ul>' . $image_str . '</ul><a href="#" class="cxc_multi_upload_image_button button' . $image . '</a><input type="hidden" class="attechments-ids ' . $name . '" name="' . $name . '" id="' . $name . '" value="' . esc_attr( implode( ',', $value ) ) . '" /><a href="#" class="cxc_multi_remove_image_button button" style="display:inline-block;display:' . $display . '">Remove media</a></div>';

}
?>

This function creates a meta box layout for the page post type.

What are the parameters?

The function takes a post object as a parameter.

The post object contains information about the current post, including its ID and title. It also has some useful methods for getting information about the current user, such as whether is it an admin or not. In this case, we use $post->ID. This returns the id of the current page/post that you are viewing in your browser. We will need this to save our data later on.

This line calls another function called cxc_multi_media_uploader_field(). It passes two arguments:

1) Name: which is an input name for the media field.

2) Value: This is the input value for the media field store value on the page.

<?php 
// Save Meta Box values.
add_action( 'save_post', 'cxc_meta_box_save' );

function cxc_meta_box_save( $post_id ) {

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
		return;
	}

	// Check the user's permissions.
	if ( ! current_user_can( 'edit_post', $post_id ) ){
		return;
	}
	
	if( isset( $_POST['cxc_post_banner_img'] ) ){
		update_post_meta( $post_id, 'cxc_post_banner_img', $_POST['cxc_post_banner_img'] );
	}
}
?>

What is the purpose of this code?

The purpose of this code is to save the value of a meta box in the database.

How does it work?

This function checks if the value of a meta box has been set and, if so, saves that value in the database using the WordPress update_post_meta().

<?php 
function cxc_add_admin_media_scripts() {
	
	wp_enqueue_style( 'admin-custom-style', get_stylesheet_directory_uri() . '/css/admin-style.css', false, '1.1', 'all' );
	if ( ! did_action( 'wp_enqueue_media' ) ) {
		wp_enqueue_media();
	}
	wp_enqueue_script( 'admin-custom-script', get_stylesheet_directory_uri() . '/js/admin-script.js', array( 'jquery' ), 1.1, true );

}
add_action( 'admin_enqueue_scripts', 'cxc_add_admin_media_scripts' );
?>

The purpose of this code is to add a custom style and script to the admin panel.

.cxc-multi-upload-medias ul li .delete-img { position: absolute; right: 3px; top: 2px; background: aliceblue; border-radius: 50%; cursor: pointer; font-size: 14px; line-height: 20px; color: red; }
.cxc-multi-upload-medias ul li { width: 120px; display: inline-block; vertical-align: middle; margin: 5px; position: relative; }
.cxc-multi-upload-medias ul li img { width: 100%; }

This code is used to style the image uploader field.

jQuery(function ($) {
      /*
       * Select/Upload image(s) event
       */
  $('body').on('click', '.cxc_multi_upload_image_button', function (e) {
    e.preventDefault();

    var button = $(this),
    custom_uploader = wp.media({
      title: 'Insert image',        
      button: {
        text: 'Use this image' 
      },
      multiple: true 
    });
    custom_uploader.on('select', function () { 
      var attech_ids = '';
      attachments
      var attachments = custom_uploader.state().get('selection'),
      attachment_ids = new Array(),
      i = 0;
      $(button).siblings('ul').empty();
      attachments.each(function (attachment) {
        attachment_ids[i] = attachment['id'];
        attech_ids += ',' + attachment['id'];
        if (attachment.attributes.type == 'image') {
          $(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.url + '" /></a><i class=" dashicons  dashicons-no delete-img"></i></li>');
        } else {
          $(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.icon + '" /></a><i class=" dashicons  dashicons-no delete-img"></i></li>');
        }

        i++;
      });

      $(button).siblings('.attechments-ids').attr('value', attachment_ids);
      $(button).siblings('.cxc_multi_remove_image_button').show();

    });
    custom_uploader.on('open',function() {
      var selection = custom_uploader.state().get('selection');
      var ids_value = $(button).siblings('.attechments-ids').val();

      if(ids_value.length > 0) {
        var ids = ids_value.split(',');

        ids.forEach(function(id) {
          attachment = wp.media.attachment(id);
          attachment.fetch();
          selection.add(attachment ? [attachment] : []);
        });
      }
    });
    custom_uploader.open();
  });

      /*
       * Remove image event
       */
  $('body').on('click', '.cxc_multi_remove_image_button', function () {
    $(this).hide().prev().val('').prev().addClass('button').html('Add  Media');
    $(this).parent().find('ul').empty();
    return false;
  });

  jQuery(document).on('click', '.cxc-multi-upload-medias ul li i.delete-img', function () {
    var ids = [];
    var attach_id =  jQuery(this).parents('li').attr('data-attechment-id');
    jQuery('.cxc-multi-upload-medias ul li').each(function () {
      if( attach_id != jQuery(this).attr('data-attechment-id') ){
        ids.push(jQuery(this).attr('data-attechment-id'));  
      }

    });
    jQuery(this).parents('.cxc-multi-upload-medias').find('input[type="hidden"]').val(ids);
    jQuery(this).parent().remove();               
  });

});

This code is used to upload multiple images using jQuery in WordPress.

Was this article helpful?
YesNo

1 comment

  1. Very nice, thank you!
    Can you please modify the code that display the image so that it will also show the caption and alternative text?

Leave a comment

Your email address will not be published.