• philiprabbett

    (@philiprabbett)


    Hi guys,

    I’ve a chunk of JS that I’ve put together to try and send the Gallery Shortcode to a custom text input field (which is hidden).

    $(document.body).on( 'click', '.insert-media', function( e ) {
    		var $this = $(this),
    			button = $this.data('editor'),
    			gallerysc = $('#'+button).val();
    
    		// Check that the input field contains a shortcode and Open the gallery with the shortcode
    		if ( gallerysc !== 'undefined' )
    			wp.media.gallery.edit( gallerysc );
    
    		// We take control of the media managers 'insert' function (it only sends the html intended for the editor)
    		wp.media.editor.insert = function( html ) {
    			$("#dh_gallery").val(html);
    			$('#wp-content-gallery-shortcode span').html($('#custom_gallery').val());
    		};
    
    		wp.media.editor.open( button );
    		return false;
    	});

    This works to an extent where it allows me to send the Gallery shortcode to the input field, and when I press ‘Add Media’, it populates with the current gallery imagery. The problem then comes from when I try to update the change, for example, remove a few images.

    The wp.media.editor.insert doesn’t appear to get called in this instance. Does anybody know the correct way of doing this?

    //disable media buttons
    add_action('admin_head', 'remove_media_buttons');
    function remove_media_buttons() {
    	global $post;
    
    	if ( $post->post_type == 'custom' && current_user_can( 'publish_posts' ) ) :
    		remove_action( 'media_buttons', 'media_buttons' );
    		add_action( 'media_buttons', 'add_new_media_button' );
    	endif;
    }
    function add_new_media_button( $editor_id = 'custom_gallery' ) {
    	static $instance = 0;
    	$instance++;
    
    	$post = get_post();
    	if ( ! $post && ! empty( $GLOBALS['post_ID'] ) )
    		$post = $GLOBALS['post_ID'];
    
    	wp_enqueue_media( array(
    		'post' => $post
    	) );
    
    	$gallery = get_post_meta( $post->ID, '_dh_product_gallery', true ); // product gallery
    	$img = '<span class="wp-media-buttons-icon"></span> ';
    
    	$id_attribute = $instance === 1 ? ' id="insert-media-button"' : '';
    	printf( '<a href="#"%s class="button insert-media add_media" data-editor="%s" title="%s">%s</a>',
    		$id_attribute,
    		$editor_id,
    		esc_attr__( 'Add Media' ),
    		$img . __( 'Add Media' )
    	);
    	printf( '<span id="wp-content-gallery-shortcode"><input type="hidden" name="custom_gallery" value="%s" id="custom_gallery"><strong>%s </strong><span>%s</span></span>',
    		esc_attr( $gallery ),
    		__( 'Gallery Shortcode:' ),
    		( $gallery ) ? esc_attr( $gallery ) : esc_attr__( 'No Gallery Attached' )
    	);
    }
  • The topic ‘Overriding 'Add Media' button to send and edit Gallery in a custom field’ is closed to new replies.