Skip to content

Instantly share code, notes, and snippets.

@vralle
Last active November 23, 2015 17:01
Show Gist options
  • Save vralle/be30857d8c1f3bd55efa to your computer and use it in GitHub Desktop.
Save vralle/be30857d8c1f3bd55efa to your computer and use it in GitHub Desktop.
Insert embed image as Shortcode by WP Media
// ### Convert an HTML-representation of an object to a string.
function myHTML() {
// Save default function
var defaultHTML = wp.html.string;
// image intercept
wp.html.string = function( options ) {
// If image, send new function
if( 'img' === options.tag ) {
return shortcake.html( options );
}
// If image inside link, send new function
if( 'a' === options.tag && 'img' === options.content.tag ) {
return shortcake.html( options );
}
// Else returns default function
return defaultHTML( options );
}
}
var shortcake = shortcake || {};
// Convert Object of attr to String
shortcake.objToString = function( attrs ) {
var attr_string = '';
_.each( attrs, function( value, attr ) {
// Fix Attr Name for href
if( 'href' === attr )
attr = 'url';
attr_string += ' ' + attr;
// Use empty attribute notation where possible.
if ( '' === value ) {
return;
}
// Convert boolean values to strings.
if ( _.isBoolean( value ) ) {
value = value ? 'true' : 'false';
}
attr_string += '="' + value + '"';
});
return attr_string;
}
// Create shortcode
shortcake.html = function( options ) {
var text = '[img',
content = options.content || '';
text += shortcake.objToString( options.attrs );
if( _.isObject( content ) ) {
text += shortcake.objToString( content.attrs );
}
return text + ']';
}
jQuery(document).ready(function(){
myHTML();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment