Skip to content

Instantly share code, notes, and snippets.

@bacoords
Last active June 10, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacoords/3101f0413b9018625b3400b51eecf558 to your computer and use it in GitHub Desktop.
Save bacoords/3101f0413b9018625b3400b51eecf558 to your computer and use it in GitHub Desktop.
how to enqueue js for a shortcode
<?php
/**
* Our theme/plugin enqueue scripts function.
*/
function example_enqueue_scripts() {
// Register the script in the normal WordPress way.
wp_register_script( 'example-shortcode-js', '...example-shortcode-script.js' );
// Grab the global $post object.
global $post;
// See if the post HAS content and, if so, see if it has our shorcode.
if ( isset( $post->post_content ) && has_shortcode( $post->post_content, 'example_shortcode' ) ) {
wp_enqueue_script( 'example-shortcode-js' );
}
}
add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );
/**
* Our Custom Shortcode.
*/
function example_shortcode_function(){
return 'Hello World!';
}
add_shortcode( 'example_shortcode', 'example_shortcode_function' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment