Including javascript for a shortcode

I’m creating a plugin that allows a user to use a shortcode. This shortcode depends on a bunch of javascript that needs to be present once the shortcode loads.

I’m having issues trying to decide when and where to load the javascript. Pieces of the code that the shortcode spits out are elements that need to be present, but aren’t available for jQuery to utilize.

Is there a specific way of loading and attaching scripts that a shortcode relies on?

function build_total_search_method( $atts ) {

    $shorcode_php_function = include( dirname(__FILE__) . "/includes/total_search.php" );

    return $shorcode_php_function;

}
add_shortcode( 'total_search', 'build_total_search_method' );

This seems to work, but it also prints a 1 to the page. Is this method okay?

2 Answers
2

Use wp_enqueue_script in your shortcode handler, in WordPress >= 3.3 it will be added to the page in the wp_footer action. Pass any data you need from PHP to JavaScript via wp_localize_script.

Leave a Comment