Add/Enqueue Scripts or Styles for pages where my plugin short code is found

So you have the neat plugin and you’re really excited about getting it done, but you don’t want this wonderful plugin loading un necessary scripts and styles for every page.

This tutorial assumes that your plugin contains the short code already, if not go here.

See the code bellow:


function my_scripts_method() {

global $post; // get the current post

if ( !empty($post) ){
 // check the post content for the short code
 if ( stripos($post->post_content, '[fbalbumsync')!==FALSE ){
 // we have found a post with the short code
 wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
 wp_enqueue_script( 'jquery' );
 // $url contains the path to your plugin folder
 $url = plugin_dir_url( __FILE__ );
 wp_enqueue_style( 'myplugin_style',$url.'1140.css' );
 wp_enqueue_script('my_plugin_js',$url.'plugin.js' );
 }
 }
}
// add scripts to wordpress front end with this hook
add_action('wp_enqueue_scripts', 'my_scripts_method');

I hope this helps you better your plugin.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s