Some weeks ago i try to find to include javascript and css on a shortcode only when the file is needed. After some search on the internet here is which i think the most efficient way.
First we must register file resource which we need, so we can call in the shortcode using wp_register_script and wp_register_style
// First register resources with init
function zz_shortcode_resource() {
wp_register_script("zz-shortcode-jscss-script", plugins_url("script.js", __FILE__), array('jquery'), "1.0", false);
wp_register_style("zz-shortcode-jscss-style", plugins_url("style.css", __FILE__), array(), "1.0", "all");
}
add_action( 'init', 'zz_shortcode_resource' );
After that we call our shortcode function with wp_enqueue_script and wp_enqueue_style
add_shortcode( 'zz_shortcode_jscss', 'zz_shortcode_jscss' );
function zz_shortcode_jscss( $attr , $content) {
$a = shortcode_atts( array(
'text' => ''
), $attr );
wp_enqueue_script( 'jquery' );
wp_enqueue_script("zz-shortcode-jscss-script",array('jquery') , '1.0', true);
wp_enqueue_style("zz-shortcode-jscss-style");
return '<div class="zz-sc-jscss">' . $a['text'] .'</div>';
}
Here is the complete source code in plugin so you can use it :
<?php
/*
Plugin Name: ZZ Shortcode With JS and CSS
Plugin URI: http://www.wpamanuke.com
Description: Include Javascript File and CSS Files on the Shortcode . Example [zz_shortcode_jscss text="HELLO CODE"][/zz_shortcode_jscss]
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/
// First register resources with init
function zz_shortcode_resource() {
wp_register_script("zz-shortcode-jscss-script", plugins_url("script.js", __FILE__), array('jquery'), "1.0", false);
wp_register_style("zz-shortcode-jscss-style", plugins_url("style.css", __FILE__), array(), "1.0", "all");
}
add_action( 'init', 'zz_shortcode_resource' );
add_shortcode( 'zz_shortcode_jscss', 'zz_shortcode_jscss' );
function zz_shortcode_jscss( $attr , $content) {
$a = shortcode_atts( array(
'text' => ''
), $attr );
wp_enqueue_script( 'jquery' );
wp_enqueue_script("zz-shortcode-jscss-script",array('jquery') , '1.0', true);
wp_enqueue_style("zz-shortcode-jscss-style");
return '<div class="zz-sc-jscss">' . $a['text'] .'</div>';
}
Here is the style.css . Because it’s only sample , so we need only little css to show that it is working
.zz-sc-jscss {
padding:30px;
background-color:#ff0000;
color:#ffffff;
}
For javascript script.js . Just showing alert for simple showing the code working
jQuery( document ).ready(function($) {
alert('This is from shortcode with js and css');
});
Ok. That’s how to include javascript and css on shortcode. I just record it , so if sometime i will need it , i just see this blog records