问题描述
如何使任何插件图标在 wordpress 的帖子?我想插入插件代码的代码将出现在 post bar [wp-admin / post.php] 中。
喜欢这个图片:
输出:如果我点击图标,它将自动将 [plugin]
写入帖子内容,如下所示:
最佳解决方案
要将我们的按钮添加到 TinyMCE 编辑器中,我们需要做几件事情:
- 将我们的按钮添加到工具栏
- 注册一个 TinyMCE 插件
- 创建 TinyMCE plug-in,告诉 TinyMCE 当我们的按钮被点击时该怎么办。
步骤#1 和#2
在这些步骤中,我们注册了我们的 TinyMCE plug-in,它将生活在'path/to/shortcode.js'
的一个 javascript 文件中 (参见下面的 wpse72394_register_tinymce_plugin()
)
// init process for registering our button
add_action('init', 'wpse72394_shortcode_button_init');
function wpse72394_shortcode_button_init() {
//Abort early if the user will never see TinyMCE
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') && get_user_option('rich_editing') == 'true')
return;
//Add a callback to regiser our tinymce plugin
add_filter("mce_external_plugins", "wpse72394_register_tinymce_plugin");
// Add a callback to add our button to the TinyMCE toolbar
add_filter('mce_buttons', 'wpse72394_add_tinymce_button');
}
//This callback registers our plug-in
function wpse72394_register_tinymce_plugin($plugin_array) {
$plugin_array['wpse72394_button'] = 'path/to/shortcode.js';
return $plugin_array;
}
//This callback adds our button to the toolbar
function wpse72394_add_tinymce_button($buttons) {
//Add the button ID to the $button array
$buttons[] = "wpse72394_button";
return $buttons;
}
步骤#3
现在我们需要创建我们的 TinyMCE plug-in 。这将进入文件'path/to/shortcode.js'
(在早期步骤中指定) 。
jQuery(document).ready(function($) {
tinymce.create('tinymce.plugins.wpse72394_plugin', {
init : function(ed, url) {
// Register command for when button is clicked
ed.addCommand('wpse72394_insert_shortcode', function() {
selected = tinyMCE.activeEditor.selection.getContent();
if( selected ){
//If text is selected when button is clicked
//Wrap shortcode around it.
content = '[shortcode]'+selected+'[/shortcode]';
}else{
content = '[shortcode]';
}
tinymce.execCommand('mceInsertContent', false, content);
});
// Register buttons - trigger above command when clicked
ed.addButton('wpse72394_button', {title : 'Insert shortcode', cmd : 'wpse72394_insert_shortcode', image: url + '/path/to/image.png' });
},
});
// Register our TinyMCE plugin
// first parameter is the button ID1
// second parameter must match the first parameter of the tinymce.create() function above
tinymce.PluginManager.add('wpse72394_button', tinymce.plugins.wpse72394_plugin);
});
次佳解决方案
把这个答案放在这里,太多了,请结帐本指南:http://wp.smashingmagazine.com/2012/05/01/wordpress-shortcodes-complete-guide/
您必须创建一个 Javascript 文件,从您通过 WordPress 注册的按钮采取行动,将 TinyMCE 按钮插入编辑器。
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。