我正在写一个插件,有许多短代码。现在,我不想在每个页面中都包含所有短代码源文件。所以我的问题是:
我应该在哪里包括来源?是后端还是前端?如何将其添加到特定页面上谢谢
我正在写一个插件,有许多短代码。现在,我不想在每个页面中都包含所有短代码源文件。所以我的问题是:
我应该在哪里包括来源?是后端还是前端?如何将其添加到特定页面上谢谢
我使用的模式是:
使用将代码分解为模块classes使用spl_autoload_register() 加载类(因此仅在使用时包含)有一个类,它是插件控制器,每个短代码都有一个方法,这些方法通常只创建短代码类的实例并传递参数,这对我来说非常有效,大大简化了事情,尤其是对于我有几十个类的大型站点。无需仔细管理包含在何处的内容,因为类autoloader会处理这些内容。
无法预测短代码的渲染位置。通常在前端,但在后端也有AJAX或自定义视图
确保在所有地方都包含回调声明。
如果源文件真的那么大,那么refactoring.
如果可以接受,我可以建议您通过重命名所有短代码来组织短代码,使它们具有相同的名称,并将旧名称放入属性中。
例如,如果有2个短代码[shortcode1 ...]
和[shortcode2 ...]
, 然后新的短代码将[myplugin_shortcode action="shortcode1" ...]
和[myplugin_shortcode action="shortcode2" ...]
.
您的插件索引文件:
<?php
/*
Plugin Name: bla bla bla
...
*/
add_shortcode(\'myplugin_shortcode\', \'wpse8170_shortcode_handler\');
function wpse8170_shortcode_handler($atts, $content = \'\') {
$atts = shortcode_atts(array(\'action\' => false), $atts);
if (empty($atts[\'action\'])) {
return \'\';
}
require_once \'shortcodes.php\';
return call_user_func_array("wpse8170_shortcode_{$atts[\'action\']}", array($atts, $content));
}
短代码。php:function wpse8170_shortcode_shortcode1($atts, $content = \'\') {
return \'...\';
}
function wpse8170_shortcode_shortcode2($atts, $content = \'\') {
return \'...\';
}
通过这样组织您的短代码,您将仅在真正需要时才包含带有短代码函数的php文件,而不管它是管理员还是前端页面。我有以下自定义帖子类型和自定义分类设置:add_action( \'init\', \'create_post_type\' ); function create_post_type() { register_post_type( \'system\', array( \'labels\' => array( \'name\' => __( \'Systems\' ),&#x