1

I am creating a shortcode in the functions.php WordPress, So that I can add my javaScript file in shortcode to call it on my website page.

1
  • check my ans plz, plz upvote and select as correct answer if it is Commented Jan 31, 2020 at 13:52

3 Answers 3

3

I wouldn't recommend adding it this way first you have to register the script using wp_register_script()

function your_shortcode_wp_enqueue_scripts_fun() {

    wp_register_script( 'cus-js1',get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.0', true );

}
add_action( 'wp_enqueue_scripts', 'your_shortcode_wp_enqueue_scripts_fun');

After that you have call it in your shortcode using wp_enqueue_script()

function get_specific_product_shortcode_function($atts){

    extract( shortcode_atts(
        array(
           'id' => '',
            ), $atts )
    );

    ob_start();


    ...
    wp_enqueue_script('cus-js1');
    ...




return ob_get_clean();
}
add_shortcode('get_specific_product_shortcode', 'get_specific_product_shortcode_function');

This is the right way to that

Sign up to request clarification or add additional context in comments.

Comments

2

You can add short code and output the content of the short parameter like this

function stackoverflow_60004550( $atts ) {
    $atts = shortcode_atts(
        array(
            'path' => 'default-path.js',
        ), $atts, 'path' );

    return '<script type="text/javascript" src="'.$atts['path'].'"></script>';
}
add_shortcode( 'jsshortcode', 'stackoverflow_60004550' );

You can then use it like this in your posts where you want to show the output path:

[jsshortcode path="https://example.com/complete-path.js"]

This can work on both page and post content as explained here: https://nabtron.com/how-to-add-javascript-file-in-wordpress-shortcode/

Comments

1

I wouldn't advise adding it this way. The shortcode is actually added shortly after the rest of the page is rendered. Instead I would add the javascript via wp_enqueue_scripts on the specific page you want to add it to. Add this to your function:

function load_scripts() {

   global $post;

   if( is_page() || is_single() )
   {
       switch($post->post_name) // post_name is the post slug
       {
           case 'some-page-slug-here':
               wp_enqueue_script('about', get_template_directory_uri() . '/js/some-js-file.js', array('jquery'), '', true);
               break;

       }
   } 
}

add_action('wp_enqueue_scripts', 'load_scripts');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.