Support

Account

Home Forums Backend Issues (wp-admin) Display ACF-Gallery in WYSIWYG Editor

Unread

Display ACF-Gallery in WYSIWYG Editor

  • Ahoi,
    i’ve integrated a custom button in the tinyMCE editor which insertes a shortcode for a gallery.

    Now i want to replace this shortcode with an image uploaded to an ACF-Image field from the same post. So far i’ve managed to find the the shortcode and replace it with an arbitrary image (using some of the code found in wp-includes/js/tinymce/plugins/wpgallery/plugin.js)

    My questions is how can i replace the shortcode with an image uploaded to the ACF-Image or Gallery field? Would be gratefull for any help or information pointing in the right direction.

    Here’s my Javascript code which does the the replacement

    (function() {
    	tinymce.PluginManager.add('my_gallery_button', function( editor, url ) {
    
    		function replaceGalleryShortcodes( content ) {
    			return content.replace( /\[my-gallery([^\]]*)\]/g, function( match ) {
    				return html( 'my-gallery', match );
    			});
    		}
    
    		function html( cls, data ) {
    			data = window.encodeURIComponent( data );
    			return '<div><img src="' + tinymce.Env.transparentSrc + '" class="my-media mceItem ' + cls + '" ' +
    			'data-my-gallery="' + data + '" data-mce-resize="false" data-mce-placeholder="1" /></div>';
    		}
    
    		function restoreMediaShortcodes( content ) {
    			function getAttr( str, name ) {
    				name = new RegExp( name + '=\"([^\"]+)\"' ).exec( str );
    				return name ? window.decodeURIComponent( name[1] ) : '';
    			}
    
    			return content.replace( /(?:<p(?: [^>]+)?>)*(<img [^>]+>)(?:<\/p>)*/g, function( match, image ) {
    				var data = getAttr( image, 'data-my-gallery' );
    
    				if ( data ) {
    					return '<p>' + data + '</p>';
    				}
    
    				return match;
    			});
    		}
    
    		// Display gallery, audio or video instead of img in the element path
    		editor.on( 'ResolveName', function( event ) {
    			var dom = editor.dom,
    				node = event.target;
    
    			if ( node.nodeName === 'IMG' && dom.getAttrib( node, 'data-my-gallery') ) {
    				if ( dom.hasClass( node, 'my-gallery') ) {
    					event.name = 'my-gallery';
    				}
    			}
    		});
    
    		editor.on( 'BeforeSetContent', function( event ) {
    				event.content = replaceGalleryShortcodes( event.content );
    		});
    
    		editor.on( 'PostProcess', function( event ) {
    			if ( event.get ) {
    				event.content = restoreMediaShortcodes( event.content );
    			}
    		});
    
    		editor.addButton( 'my_gallery_button', {
    			name: 'Gallery',
    			icon: 'my-gallery',
    			onclick: function() {
    				editor.insertContent('[my-gallery]');
    			}
    		});
    	});
    })();
Viewing 1 post (of 1 total)

The topic ‘Display ACF-Gallery in WYSIWYG Editor’ is closed to new replies.