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:

[sourcecode language=”php”]

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’);

[/sourcecode]

I hope this helps you better your plugin.

Published by

Dwain Maralack

Servant, Husband, Software Engineer and all round fun-loving guy, I work as a Developer at WooThemes.

Leave a Reply