I want load some scripts and style only for a specific shortcode. I used
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my_shortcode') ) {}
It works when I put my shortcode on page but it does not work when I put my shortcode in page template. Like the following one in index.php file:
echo do_shortcode( ' [ my_shortcode ] ' );
Is there any way to load scripts for [ my_shortcode ] in do_shortcode(' [ my_shortcode ] ') without checking page template.
I want load some scripts and style only for a specific shortcode. I used
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my_shortcode') ) {}
It works when I put my shortcode on page but it does not work when I put my shortcode in page template. Like the following one in index.php file:
echo do_shortcode( ' [ my_shortcode ] ' );
Is there any way to load scripts for [ my_shortcode ] in do_shortcode(' [ my_shortcode ] ') without checking page template.
Share Improve this question asked Jan 29, 2017 at 15:56 sayfulsayful 1012 bronze badges 1 |2 Answers
Reset to default 2Add a filter to pre_do_shortcode_tag
and check if $tag is the same as your shortcode tag. If it is, enqueue a script in the footer.
add_filter( 'pre_do_shortcode_tag', function( $a, $tag, $attr, $m ) {
if( 'my_shortcode_tag' === $tag ) {
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer = true );
}
return $a;
}, 10, 4 );
I think there is a better way to enqueue or load your scripts first register the script or styles with wp_register_style
and wp_register_script
.
After registering you can load the script/style when required. For example when you render a shortcode with wp_enqueue_style("your_style") and wp_enqueue_script("your_script").
Example
[my_shortcode other parameters]
Add action for the script by registering and enqueuing when required.
function prefix_my_shortcode_wp_enqueue_scripts() {
wp_register_script( 'my-shortcode-script', plugins_url( 'path/myscript.css' ) );
}
add_action( 'wp_enqueue_scripts', 'prefix_my_shortcode_wp_enqueue_scripts' );
Your shortcode function
function prefix_function_my_shortcode( $attributes ) {
extract( shortcode_atts(
// your shortcode array args
));
wp_enqueue_script( 'my-shortcode-script' );
return 'your shortcode output;
}
add_shortcode( 'my_shortcode', 'prefix_function_my_shortcode' );
Hope that answers your question. Let me know if that helps out.
get_page_template
to get the template path for current page, e.gprint_r( has_shortcode(file_get_contents(get_page_template()), "my_shortcode") );
– Ismail Commented Jan 29, 2017 at 16:50