我创建自己的短代码已经有一段时间了,这非常有帮助。我想知道是否有一种方法可以添加一个按钮,就在默认的 WordPress 编辑器上方,类似于“添加媒体”按钮,即“添加短代码”,单击它时 - 会自动插入可用的短代码列表进入文本编辑器字段,然后或者当然可以手动更改短代码中的任何详细信息。只是认为这可能比保留带有短代码的文本文档来复制和粘贴更容易。
这是一个完整的解决方案。
// Php - 添加到 function.php 中
function rawebdev_shordcode_dialog_template() {
// template for the dialog
$dialog = '<div id="custom-shortcode-url" class="hidden" >';
$dialog .= '<input type="text"
placeholder="[myshortcode]"
name="custom-shortcode-url-input"
id="custom-shortcode-url-input" />';
$dialog .= '</div>';
echo $dialog;
}
add_action('admin_footer', 'rawebdev_shordcode_dialog_template');
function rawebdev_custom_button_after_addmedia() {
echo '<a href="#" id="rawebde-shortcode-btn" class="button">Add Shortcode</a>';
}
add_action('media_buttons', 'rawebdev_custom_button_after_addmedia', 25);
function rawebdev_shortcode_button_js_file() {
// include file only in admin area
if( is_admin() ){
// JS
wp_enqueue_script(
'rawebdev_shortcode_button_js', // handle
plugin_dir_url( __FILE__ ) . 'js/shortcode-button.js',// source
array('jquery-ui-dialog' ), // dependencies
fileatime( plugin_dir_path(__FILE__) . 'js/shortcode-button.js' ) // version
);
wp_enqueue_style ( 'wp-jquery-ui-dialog');
}
}
add_action('wp_enqueue_media', 'rawebdev_shortcode_button_js_file');
创建一个文件-shortcode-button.js并添加一个片段
jQuery(function ($) {
$(document).ready(function () {
// creation of the dialog
$('#custom-shortcode-url').dialog({
title: 'Insert Shortcode',
autoOpen: false,
draggable: false,
width: 'auto',
modal: true,
resizable: false,
closeOnEscape: true,
buttons: {
"Insert Shortcode": function () {
let str = $('#custom-shortcode-url-input').val();
// insert text in editor
wp.media.editor.insert(str);
// close dialogue
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#rawebde-shortcode-btn').click(function () {
$('#custom-shortcode-url-input').val('[mycustomshortcode]');
$('#custom-shortcode-url').dialog('open');
});
});
});
输出: