15

I'm learning about plugins and shortcodes. I noticed that when I activate my plugin its code gets loaded on all of my pages-- even pages that don't have my shortcode. (I don't mean content vs. admin pages). On some content pages, I use a particular shortcode and on other content pages, I don't-- but in any case, the plugin's code is loaded. How do I make it so that the the plugin is included only on pages where the shortcode is used?

More Detail:

Let's say I've got a plugin that makes a lightbox. I activate the plugin. On my "Cool Images" page, I use shortcode to make a lightbox. When I check View Source on my "About" page, which doesn't use the lightbox shortcode, I see that the lightbox plugin's code has been loaded. My pages will load faster if I write my plugin so that its code is only loaded on the pages where it's needed. Is this possible? Otherwise, I'll have code for lots of plugins loaded on pages unnecessarily. Any ideas?

4
  • 1
    Are you trying to enqueue something, or trying to execute a PHP script on pages that have the shortcode?
    – mor7ifer
    Commented Jan 9, 2012 at 1:09
  • +1 @m0r7if3r - I also would like to understand that ..The approaches would be very different
    – krembo99
    Commented Jan 9, 2012 at 5:50
  • @mrOr7if3r, Thanks for the message. For example, let's say I've got a Google Maps plugin. Does that plugin have to be loaded on every page-- i.e. pages that don't use the plugin? Let's say I have an "About" page which doesn't have the Google Maps shortcode on it. If I look at View Source, I see that the plugin's code was loaded on that page (event though I'm not using). Does code for plugins have to load on every single page? Thanks.
    – Laxmidi
    Commented Jan 9, 2012 at 17:41
  • Good question which imho leads to (new) best practice, as WP now enables us to enqueue scripts at any point in time.
    – Raphael
    Commented Jan 25, 2012 at 12:06

6 Answers 6

9

WP v3.3 gave us the ability to run wp_enqueue_script in the middle of a page. Ticket 9346

This has made it much easier to include your JS with better granularity (when using shortcodes, at least). Here, jquery will be only included when our shortcode is fired.

function get_slideshow() {
  // Do some stuff...

  // Load up scripts right from within our shortcode function (requires WP 3.3+)
  wp_enqueue_script( 'jquery', array(), null, true  ); 

  return;
}
add_shortcode( 'cool_slideshow', 'get_slideshow' );
2
  • 1
    This is how it should be done, imo.
    – Raphael
    Commented Jan 25, 2012 at 12:06
  • 1
    Excellent, I hadn't realised it was now possible to run wp_enqueue_script in the middle of a page. A much cleaner way to only load scripts / css when needed! Commented Feb 10, 2012 at 15:48
2

Check for admin UI variables

One menu item is a special case: Comments, as they get registered using the add_WHATEVER_(submenu)page() API.

// All need to be stated as beeing global
global $pagenow, $typenow, $hook_suffix, $parent_file, $submenu_file, $post_type_object;
if ( 'THE-OUTPUT.php' === $WHATEVER_YOU_CHOOSE_TO_CHECK )
    // do stuff

These are non-consitent and hardcoded into wp core. Note that not all are set on all pages.

Hook into page-specific admin UI hooks

Then there're also special, page-specific hooks, that you can take a look at in admin-footer.php and admin-header.php:

// Examples:
// Header
"admin_head-$hook_suffix"
"admin_print_styles-$hook_suffix"
"admin_print_scripts-$hook_suffix"
// Footer
"admin_footer-$hook_suffix"

Some examples in the real world: Post Screen

// Examples how the result looks like
admin_print_styles-post.php
admin_print_styles-post-new.php

Then there's also the $hook_suffix that you can check against for enqueueing scripts, right when you're hooking your action:

do_action( 'admin_enqueue_scripts', $hook_suffix );

Update

To get easier (1-click) access to this data/info, we built a freely available, developer friendly plugin named "(WCM) Current Admin Info", which is available on GitHub. The plugin can in the near future also be found in the official wp.org repository.

Screen shots

To give a preview of what you get with this plugin:

Screen

Hooks

Globals

1

@kaiser noted get_shortcode_regex() several times in this thread, I just thought I give an example on how to use it. The code is pretty much taken from the get_shortcode_regex() WordPress Code Reference page.

function enqueue_script_if_shortcode_is_detected() {
    global $post;

    wp_register_script( 'your-script', $the_path_to_your_script, '1.0', true );

    $pattern = get_shortcode_regex();

    if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
        && array_key_exists( 2, $matches )
        && in_array( 'your-shortcode', $matches[2] )
    ) {
        wp_enqueue_script('your-script');
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_script_if_shortcode_is_detected' );
0

Could do something along the lines of (in the header.php):

<?php
        if ( have_posts() && ( is_page() || is_single() ) ) {
            $content = get_the_content(the_post());
            if ( stripos( $content , '[your-shortcode') ) { function_for_scripts(); } 
        }   
?>

Checks if current load is page or post, then grabs content and searches for your shortcode. Upon finding it, it executes your function.

3
  • Thank you for your message. I tried using your solution, but, unfortunately, I couldn't get it to work.
    – Laxmidi
    Commented Jan 25, 2012 at 6:10
  • Was added to the header?
    – Noel Tock
    Commented Jan 25, 2012 at 7:09
  • 1
    Have you already seen get_shortcode_regex()?
    – kaiser
    Commented Feb 7, 2014 at 16:11
0

The simplest way is to just check for the shortcode.

function your_scripts()
{ 
    global $post;
    wp_register_script('your-script',$the_path_to_your_script,'0.1',true);
    if ( strstr( $post->post_content, '[your-shortcode' ) ) 
    {
        wp_enqueue_script('your-script');
    }
}
add_action( 'wp_enqueue_scripts', 'your_scripts');
1
-3

I found this solution:

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );

function my_deregister_javascript() {
    wp_deregister_script( 'my_scripts_handle' );
}
1
  • 3
    But you solutions will remove scripts from all pages
    – Mamaduka
    Commented Jan 25, 2012 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.