post-page

Adding Scripts Properly to WordPress Part 3 – Page Detection

12
responses
by
 
on
May 8th, 2010
in
HOW-TO, WordPress FAQs

You might find yourself in the situation where you only want a script to run on a certain page. In fact, it’s good practice to only load your JavaScript files when absolutely necessary; loading the files on every single page is a big no-no (I’ve been chastised before for this).

While on the blog’s front-end, WordPress makes it super-easy with its conditional tags.

I’m not going to go over the conditional tags here, but here are a few you can take advantage of:

While being selective on the front-end is relatively straightforward, the admin-panel is another monster.

Sure, there’s the is_admin() conditional, but what if you only want to run a script in a certain section within the admin panel?

One technique is to use the PHP reserved variable called $_GET.

Say you have a plugin options page with a URL of:

http://www.mydomain.com/wp-admin/options-general.php?page=my-plugin-file.php

You can use the $_GET variable to capture the page and run a conditional to determine if the page is yours.

<?php
if (isset($_GET['page'])) { 
    if ($_GET['page'] == "my-plugin-file.php") {
        /*load your scripts here */
    }
}
?>

If there are no variables to capture, you may have to use the reserved variable $_SERVER to capture the page name. From there, you would use a conditional or a switch statement.

<?php
switch (basename($_SERVER['SCRIPT_FILENAME'])) {
    case "edit-comments.php":
               /*load scripts here*/
        break;
    case "upload.php":
               /*load other scripts here*/
        break;
    default:
        break;
}
?>

A Real-World Example

For a WordPress plugin I modified (WP Grins Lite – I’m not the original author), I wanted to include the JavaScript file only on specific pages.

In the admin panel, I wanted the script to load when adding/editing posts and pages, and when editing a comment.

On a post, I wanted the script to load only on posts and pages. To make things interesting, I also wanted to only load the script if comments were open.

<?php
function add_scripts(){
    global $post;
    if (is_admin()) {
        switch (basename($_SERVER['SCRIPT_FILENAME'])) {
            case "post.php":
            case "post-new.php":
            case "page.php":
            case "page-new":
            case "comment.php":
                break;
            default:
                return;
        }
    } else if ((!is_single() && !is_page()) || 'closed' == $post->comment_status) {
        return;
    } 
    wp_enqueue_script('wp_grins_lite', plugins_url('wp-grins-lite') . '/js/wp-grins.js', array("jquery"), 1.0); 
    wp_localize_script( 'wp_grins_lite', 'wpgrinslite', $this->get_js_vars());
}
?>

And there you have it. Page detection in a nutshell.

This article is an excerpt from Ronald Huereca’s e-book entitled WordPress and Ajax (used with permission).

heading
12
Responses

 

Comments

  1. Hikari (26 comments.) says:

    There are special actions that are only available in specific admin pages, that’s the right way to identify in which page you are.

    I have a plugin that helps us to identify these special actions. It also lists all conditional tags in a unique place and all hooks with functions hooked to them.

    http://Hikari.ws/hooks-troubleshooter/

    • Ronald huereca (32 comments.) says:

      But, only admin_print_scripts should you add script files. Is there an additional page-detection technique you can use within this hook?

      • Hikari (26 comments.) says:

        You can hook those actions, and inside them add the script. It may be better than hooking on every admin page and testing current page to add the script.

  2. Otto (215 comments.) says:

    Using GET and SERVER is a pretty terrible way to detect what page you’re on. The global $pagenow is what you should be checking. That can be things like edit.php, or options-general.php.. Depending on what page you’re on.

    But really, you should use the proper hooks to add them only to the pages you’re interested in.

    One of the hooks in the admin section is this one:

    do_action(“admin_print_scripts-$hook_suffix”);

    That ‘hook_suffix’ is special. It can be set to a lot of things, but one thing it does get set to for admin pages is the global $pagenow variable.

    So, to enqueue something only on, say, post-new.php, you could do this:

    function eee() {
    wp_enqueue_script(…);
    }
    add_action(‘admin_print_scripts-post-new.php’,'eee’);

    Much simpler and safer than relying on untrustworthy data. Never resort to the Superglobals when WP offer nicer ways to do things.

    • Ronald huereca (32 comments.) says:

      Coolness. I learned something today ;)

      I will update this post when I update my book. Thanks for sharing.

      Can you also do the same type of thing with wp_print_scripts?

      • Otto (215 comments.) says:

        No, that stuff is really only for the admin. Generally you use the is_home and similar for the front end view of things.

    • Ankur Oberoi (4 comments.) says:

      Where can I find more documentation about the possible hook_suffix’s? I wasn’t able to find it in the Codex. I am specifically looking to figure out if I can detect if I am on an Add or Edit page for a custom post type. Any help would be appreciated. Thanks!

    • Ankur Oberoi (4 comments.) says:

      i think i figured it out, or i at least have one solution to the question i was asking. let me know if you might know of a better solution or any holes i might have missed. (in this example my custom post type is called `slider`)

      in functions.php:

      function my_media_upload_scripts() {
      wp_enqueue_script(`my-script`, content_url(`/themes/twentyten/my-script.js`) , array(‘jquery’), ’0.2′, true);
      }

      add_action(`admin_print_scripts-post.php`, `my_scripts`);

      in my-script.js:

      if (pagenow == ‘slider’) {
      jQuery(document).ready(function() {

      jQuery(‘#titlediv’).css(‘background-color’, ‘red’);

      });
      }

      i am not sure if this pagenow variable is always available or if another plugin I am using made that available for me. does anyone know where it comes from?

      • Ankur Oberoi (4 comments.) says:

        yikes, sorry for the overload, i couldnt edit my post when it was awaiting moderation.

        i meant:

        function my_scripts() {

        int he functions.php file. excuse the typo.

  3. Andrew@BloggingGuide (90 comments.) says:

    This will be handy in the future. Thanks for sharing this.

  4. bubazoo (213 comments.) says:

    so do you mean running a script without activating it in the plugins area? I mean, isn’t a script or plugin activated on all pages as soon as its activated?



Obviously Powered by WordPress. © 2003-2013

page counter
css.php