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.

Read More

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?

Related posts

Leave a Reply

2 comments

  1. The wp_enqueue_script() include the wp_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 uses json_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.

    add_action( 'admin_enqueue_scripts', 'fb_print_scripts' );
    function fb_print_scripts() {
        global $current_screen;
    
        if ( isset( $current_screen -> id ) && ! in_array( $current_screen -> id, array( 'post', 'page' ) ) )
            return;
    
        if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) )
            $options = get_site_option( 'my_options_id' );
        else
            $options = get_option( 'my_options_id' );
    
        if ( ! $options )
            return;
        ?>
        <script type="text/javascript">
            var my_json_object = <?php echo json_encode( $options ); ?>;
        </script>
        <?php
    }