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.
-
check my ans plz, plz upvote and select as correct answer if it isNabeel Khan– Nabeel Khan2020-01-31 13:52:40 +00:00Commented Jan 31, 2020 at 13:52
3 Answers
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
Comments
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
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');