post-page
  • AgentPress Real Estate WordPress Themes

Adding Scripts Properly to WordPress Part 3 – Page Detection

9
responses
by
Ronald Huereca 
on
May 8th, 2010
in
HOW-TO

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).

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading ... Loading ...
heading
9
Responses

 

Comments

  1. Hikari (25 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 (25 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 (179 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 (179 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.

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

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

  4. bubazoo (212 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?



Leave a Comment

Obviously Powered by WordPress. © 2003-2010 MidOut LLC

page counter