This post is a part 1 of Create a WordPress Post Editor Button to Add Shortcode post series.
In this tutorial we will see how to add buttons to WordPress text editor. This can be useful while creating a shortcode where you want to add the shortcode tags with just a click instead of typing it.
We need to use WordPress Quicktags API to add a button to the WordPress text editor.
Here is an example code snippet which adds a button to the WordPress code editor and wraps the selected text using [code][/code]
tags.
function shortcode_button_script()
{
if(wp_script_is("quicktags"))
{
?>
<script type="text/javascript">
//this function is used to retrieve the selected text from the text editor
function getSel()
{
var txtarea = document.getElementById("content");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
return txtarea.value.substring(start, finish);
}
QTags.addButton(
"code_shortcode",
"Code",
callback
);
function callback()
{
var selected_text = getSel();
QTags.insertContent("[code]" + selected_text + "[/code]");
}
</script>
<?php
}
}
add_action("admin_print_footer_scripts", "shortcode_button_script");
{
if(wp_script_is("quicktags"))
{
?>
<script type="text/javascript">
//this function is used to retrieve the selected text from the text editor
function getSel()
{
var txtarea = document.getElementById("content");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
return txtarea.value.substring(start, finish);
}
QTags.addButton(
"code_shortcode",
"Code",
callback
);
function callback()
{
var selected_text = getSel();
QTags.insertContent("[code]" + selected_text + "[/code]");
}
</script>
<?php
}
}
add_action("admin_print_footer_scripts", "shortcode_button_script");
Here is how it looks