admin管理员组文章数量:1312952
In a plugin I declared a shortcode, but I want to enqueue the scripts only on those pages which have the shortcode. I tried this:
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'MyShortCode') ) {
wp_enqueue_style('style_ui');
wp_enqueue_script('script_ui');
}
It is working fine until I am adding the shortcode inside a template directly.
echo do_shortcode( '[MyShortCode]' );
I also enqueued scripts inside the shortcode function:
public function shortcodeui($atts) {
wp_enqueue_style('style_ui');
wp_enqueue_script('script_ui');
require_once MYPL_PATH. 'templates/public/public.php';
}
But its not working for the template.
In a plugin I declared a shortcode, but I want to enqueue the scripts only on those pages which have the shortcode. I tried this:
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'MyShortCode') ) {
wp_enqueue_style('style_ui');
wp_enqueue_script('script_ui');
}
It is working fine until I am adding the shortcode inside a template directly.
echo do_shortcode( '[MyShortCode]' );
I also enqueued scripts inside the shortcode function:
public function shortcodeui($atts) {
wp_enqueue_style('style_ui');
wp_enqueue_script('script_ui');
require_once MYPL_PATH. 'templates/public/public.php';
}
But its not working for the template.
Share Improve this question edited Dec 19, 2020 at 10:28 cjbj 15k16 gold badges42 silver badges89 bronze badges asked Dec 19, 2020 at 7:17 devdev 33 bronze badges1 Answer
Reset to default 0Assuming the first block of code is executed when your plugin is launched, the has_shortcode
function is prescanning the post content to check if the shortcode is present. You then enqueue the scripts. That will work, because plugins are initiated before the scripts are enqueued (init
hook comes before wp_enqueue_scripts
hook).
If you enqueue scripts inside the shortcode, the function will be executed when the post content is assembled. At that point WP is already past the wp_enqueue_scripts
hook. The scripts will then end up in the footer, which may impact their behaviour.
If you use do_shortcode
directly in a template, your function with has_shortcode
will do nothing, because it only reacts to stuff that is inside the post content. You will have to replicate the circumstances under which do_shortcode
will be executed in the template during plugin initialisation to enqueue the scripts.
本文标签: pluginsHow to check if short code is present in template
版权声明:本文标题:plugins - How to check if short code is present in template? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741905782a2404135.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论