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?
Use
wp_enqueue_script
in your shortcode handler, in WordPress >= 3.3 it will be added to the page in thewp_footer
action. Pass any data you need from PHP to JavaScript viawp_localize_script
.The
wp_enqueue_script()
include thewp_localize_script()
is the right solution. Parse the arguments of the shortcode or enqueue always the script.If you have many data and you will use this in a Json object. Some hints, which should help, if it comes to problems or which link to solutions via JSON directly.
The function
wp_localize_script()
decodes HTML Entities, which is kind of important, but not always the perfect solution. The function usesjson_encode()
, which can let to problems in multi-dimensional arrays in connection with the decoding of entities. The alternative solution is to send data as json object, like the example below.