Skip to content

Instantly share code, notes, and snippets.

@keithdevon
Created August 20, 2015 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithdevon/1f01ec4d0d1a7d4d43d7 to your computer and use it in GitHub Desktop.
Save keithdevon/1f01ec4d0d1a7d4d43d7 to your computer and use it in GitHub Desktop.
WordPress Plugin template with conditional style/script loading
<?php
/*
Plugin Name: Plugin Name
Description: Description
Version: 0.1
Author: White Rock Design
Author URI: http://keithdevon.com
*/
// block direct access
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
// load the plugin script if the $add_sex_degress_script global variable is true
add_action('init', 'register_plugin_script');
add_action('wp_footer', 'print_plugin_script');
function register_plugin_script() {
wp_register_script('plugin-script', plugins_url('plugin-script.js', __FILE__), array('jquery'), '1.0', true);
}
function print_plugin_script() {
global $add_plugin_script;
if ( ! $add_plugin_script )
return;
wp_print_scripts('plugin-script');
}
//[my_shortcode]
function my_shortcode_func( $atts ){
// set to true so that the plugin script is loaded when the shortcode is called
global $add_plugin_script;
$add_plugin_script = true;
// load the stylesheet in the head
$plugin_url = plugin_dir_url( __FILE__ );
$css_url = $plugin_url . 'style.css';
$html = "<script>jQuery(document).ready(function($) {
$('head').prepend($('<link>').attr({
rel: 'stylesheet',
type: 'text/css',
media: 'screen',
href: '" . $css_url . "'
}));
});
</script>";
$html .= '<h1>Hello World!</h1>';
return $html;
}
add_shortcode( 'my_shortcode', 'my_shortcode_func' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment