Last active
February 6, 2017 00:03
-
-
Save trepmal/5000914 to your computer and use it in GitHub Desktop.
Extract attachment IDs from selection, reinsert as gallery shortcode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Plugin Name: Convert to Gallery | |
//Description: Extract attachment IDs from selection, reinsert as gallery shortcode. Use "convert to gallery" button in Text mode. Usefull if you accidentally bulk insert a number of images instead of inserting as gallery. | |
add_action( 'admin_print_footer_scripts', 'convert2gallery_quicktag', 100 ); | |
function convert2gallery_quicktag() { | |
?> | |
<script type="text/javascript"> | |
QTags.addButton( 'convert2gallery', 'convert to gallery', extract_and_convert ); | |
function extract_and_convert(e, canvas, ed) { | |
var sel, startPos, endPos, scrollTop, text; | |
if ( document.selection ) { //IE | |
canvas.focus(); | |
sel = document.selection.createRange(); | |
selection = sel.text; | |
content = extract_attachment_ids( selection ); | |
sel.text = content; | |
canvas.focus(); | |
} else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera | |
text = canvas.value; | |
startPos = canvas.selectionStart; | |
endPos = canvas.selectionEnd; | |
scrollTop = canvas.scrollTop; | |
selection = text.substring( startPos, endPos ); | |
content = extract_attachment_ids( selection ); | |
canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length); | |
canvas.focus(); | |
canvas.selectionStart = startPos + content.length; | |
canvas.selectionEnd = startPos + content.length; | |
canvas.scrollTop = scrollTop; | |
} else { | |
canvas.value += content; | |
canvas.focus(); | |
} | |
return true; | |
} //end extract_and_convert | |
function extract_attachment_ids( string ) { | |
test = /wp-image-(\d*)/g.test( string ); | |
if ( ! test ) { | |
alert( 'No attachment IDs found in selection.'); | |
return string; | |
} | |
var matches = string.match(/wp-image-(\d*)/g); | |
gal = '[gallery ids="'; | |
for ( var ind in matches ) { | |
var attid = matches[ind].match( /(\d+)/g ); | |
gal += attid[0] +','; | |
} | |
gal += '"]'; | |
return gal; | |
} | |
</script> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment