如何让WordPress的has_shortcode检测模板中的do_shortcode?
解决
has_shortcode无法检测模板中短代码的问题 由于$post->post_content仅包含文章/页面的编辑内容,无法覆盖模板中直接调用的短代码,以下是几种可行的解决办法:
方法一:通过全局变量标记模板使用了短代码
在模板中调用短代码前,设置全局变量标记,后续在检测函数中判断该标记:
模板代码修改:
<html> ... <?php // 标记当前模板使用了my_shortcode $GLOBALS['has_my_shortcode_in_template'] = true; do_shortcode( '[my_shortcode]' ); ?> ... </html>
functions.php中的函数修改:
function my_function() { $has_shortcode = has_shortcode( $post->post_content, 'my_shortcode' ); // 同时检查模板里的标记 $has_template_shortcode = isset( $GLOBALS['has_my_shortcode_in_template'] ) && $GLOBALS['has_my_shortcode_in_template']; if ( $has_shortcode || $has_template_shortcode ) { // 加载短代码所需的样式表等操作 } }
方法二:将资源加载逻辑绑定到短代码回调(推荐)
直接在短代码的回调函数中处理资源加载,只要短代码被执行(不管是在文章内容还是模板里),就自动加载所需资源,无需额外检测:
function my_shortcode_callback() { // 注册并加载样式表,wp_enqueue_style会自动避免重复加载 wp_enqueue_style( 'my-shortcode-styles', get_template_directory_uri() . '/css/my-shortcode.css', array(), '1.0.0' ); // 返回短代码的输出内容 return '<div class="my-shortcode-container">短代码内容</div>'; } add_shortcode( 'my_shortcode', 'my_shortcode_callback' );
这种方式更可靠,资源加载和短代码执行强关联,不会出现漏检测的情况。
方法三:针对特定模板进行检测
如果短代码只在特定页面模板中使用,可以直接检测当前页面是否使用了该模板,结合文章内容的检测:
function my_function() { $uses_shortcode = has_shortcode( $post->post_content, 'my_shortcode' ); // 检查当前页面是否使用了包含短代码的模板(替换成你的模板文件名) if ( is_page_template( 'custom-template.php' ) ) { $uses_shortcode = true; } if ( $uses_shortcode ) { // 执行资源加载等操作 } }
内容的提问来源于stack exchange,提问作者wileyCoyote
相关产品推荐
相关产品推荐

