我有一个插件,它在激活时创建一个页面,然后在停用时删除它。作为页面创建的一部分,我想在帖子内容中使用一个短代码,所以我添加了一个带有add_shortcode() 第一
出于调试目的,我立即使用shortcode_exists() 并打印出相应的日志语句。日志表明存在短代码。在自动创建的页面上,它只显示短代码名称[myplugin_reference]. 即使手动创建页面并插入短代码,也会得到相同的结果。
我甚至安装了一个简单的plugin - JSM\'s Show Registered Shortcodes 其中显示了已注册的短代码列表,而我的短代码不在列表中。
这是我的代码:
function install_myplugin() {
add_shortcode( \'myplugin_reference\', \'myplugin_shortcode_reference\' );
if ( shortcode_exists( \'myplugin_reference\' ) ) {
error_log( \'Shortcode "myplugin_reference" added successfully\' );
} else {
error_log( \'Shortcode "myplugin_reference" not added\' );
}
$templates = get_page_templates();
$post = array(
\'post_title\' => __( \'Thank You\', \'myplugin-payment-gateway\' ),
\'post_content\' => \'[myplugin_reference]\',
\'post_status\' => \'publish\',
\'post_name\' => \'myplugin-thank-you\',
\'post_type\' => \'page\'
);
if ( isset( $templates[\'Full width\'] ) ) {
$post[\'page_template\'] = $templates[\'Full width\'];
}
$page_id = wp_insert_post( $post, true );
add_option( \'myplugin_thankyou_page_id\', $page_id );
}
function uninstall_myplugin() {
$page_id = get_option( \'myplugin_thankyou_page_id\' );
if ( $page_id ) {
wp_delete_post( $page_id, true );
delete_option( \'myplugin_thankyou_page_id\' );
}
if ( shortcode_exists( \'myplugin_reference\' ) ) {
remove_shortcode( \'myplugin_reference\' );
}
}
function myplugin_shortcode_reference() {
wp_enqueue_script( \'jquery\' );
ob_start();
?>
<span id="payment-ref"></span>
<script type="text/javascript">
jQuery(function($) {
let params = {},
paramPairs = (window.location.search).replace(/^\\?/, \'\').split("&");
// get querystring params
paramPairs.reduce((acc, current) => {
const nameValue = current.split("=");
return params[nameValue[0]] = decodeURIComponent(nameValue[1]);
}, "");
if (!!params.reference) {
$(\'#payment-ref\').html(params.reference);
}
});
</script>
<?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
// Activation, Deactivation hooks
register_activation_hook( __FILE__, \'install_myplugin\' );
register_deactivation_hook( __FILE__, \'uninstall_myplugin\' );
页面上显示的内容如下:

最合适的回答,由SO网友:Jacob Peattie 整理而成
您只在激活时注册了短代码。add_shortcode() 不是持久性的,并且由于短代码是在输出时解析的,所以需要在每个请求上注册短代码。所以你需要搬家add_shortcode() 激活挂钩外部:
function install_myplugin() {
// ...
}
function uninstall_myplugin() {
// ...
}
function myplugin_shortcode_reference() {
// ...
}
// Activation, Deactivation hooks
register_activation_hook( __FILE__, \'install_myplugin\' );
register_deactivation_hook( __FILE__, \'uninstall_myplugin\' );
add_shortcode( \'myplugin_reference\', \'myplugin_shortcode_reference\' );