Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

So I continue to run into this issue and I just looking for the best and simplest solution to solve this problem.

I have come to make use of custom post types in many different projects and have extended these with custom metaboxes which I have then further extended by adding custom scripts such as jQuery event calendar selectors... All of this works great except for one key issue... I don't want these custom jQuery scripts to load on every page in the admin.

I am essentially just looking for a way to just have these custom jquery fields loaded when I am on the "edit post" page for a SPECIFIC post type.

What's the best solution here?


UPDATE 1

First of all, thank you very much.

I am actually shocked that plugin developers dont make sure of things like this because as I am finding out this is one of the key reasons that problems exist with different plugins.

I am having some further issues though with this. For example...

I have modified the script to call the if statement like this:

if (is_admin() && $pagenow=='post-new.php' OR $pagenow=='post.php' && $typenow=='events')

As you can see I am trying to set things up so that my scripts ONLY get called when I am adding or editing a post within the post type of "events".

I don't want the script to load on any other page and also don't want it to run on the list of page within the post type of "events" so I would think the if statement is correct.

The problem however seems to be that the script only gets loaded when I create a new post within this post type but it does not seem to work when I am editing an existing post.

Could you test this out and maybe let me know what I could be doing wrong?

Here is the exact code which I am using... maybe there is a better or simple way of doing this?

<?php
// INCLUDE METABOX CUSTOM JQUERY DATEPICKER 2
add_action('admin_init','load_admin_datapicker_script');
function load_admin_datapicker_script() {
  global $pagenow, $typenow;
  if (is_admin() && $pagenow=='post-new.php' OR $pagenow=='post.php' && $typenow=='events') {
    $ss_url = get_bloginfo('stylesheet_directory');
    wp_enqueue_script('jquery');
    wp_enqueue_script('custom_js_jquery_ui',"{$ss_url}/admin-metabox/js/jquery-ui-1.7.1.custom.min.js",array('jquery'));
    wp_enqueue_script('custom_js_daterangepicker',"{$ss_url}/admin-metabox/js/daterangepicker.jQuery.js",array('jquery'));
    wp_enqueue_script('custom_js_custom',"{$ss_url}/admin-metabox/js/custom.js",array('jquery'),NULL,TRUE);
    wp_enqueue_style('custom_css_daterangepicker',"{$ss_url}/admin-metabox/css/ui.daterangepicker.css");
    wp_enqueue_style('custom_css_jquery_ui',"{$ss_url}/admin-metabox/css/redmond/jquery-ui-1.7.1.custom.css");
  }
}

Also... if I wanted to add three post types and load different JS scripts for each post types then would I just duplicate the code above three separate times or is this not a good way of doing this? For example... would it be better to just call: global $pagenow, $typenow; At the top of my functions file or does it matter or complicate things when I duplicate it more than once?

On a different problem related to the same... I for example am utilizing the "gravity forms" plugin but I have noticed their scripts run on every page on the admin which is causing issues with other plugins. How would i go about modifying their script to ensure the scripts only get loaded when I need them.


UPDATE 2

I have modified my functions.php file with the code provided by Mike (below) however it seems that the applicable javascript is still being included when you create a NEW Post or Page. This means that when you attempt to create a NEW Post or Page either by creating a new default wordpress post/page or when you create a NEW post/page based off one of your custom post types. The code proposed by Mike IS working on all other admin pages and it DOES work when you "EDIT" an existing post/page or custom post type. Any suggested modifications to make this work correct?

Here is my current code:

<?php
   add_action('admin_init','load_admin_datapicker_script');
   function load_admin_datapicker_script() {
    global $pagenow, $typenow;
    if (empty($typenow) && !empty($_GET['post'])) {
        $post = get_post($_GET['post']);
        $typenow = $post->post_type;
    }
    if (is_admin() && $pagenow=='post-new.php' OR $pagenow=='post.php' && $typenow=='events') {
        $ss_url = get_bloginfo('stylesheet_directory');
        wp_enqueue_script('jquery');
        wp_enqueue_script('custom_js_jquery_ui',"{$ss_url}/admin-metabox/js/jquery-ui-1.7.1.custom.min.js",array('jquery'));
        wp_enqueue_script('custom_js_daterangepicker',"{$ss_url}/admin-metabox/js/daterangepicker.jQuery.js",array('jquery'));
        wp_enqueue_script('custom_js_custom',"{$ss_url}/admin-metabox/js/custom.js",array('jquery'),NULL,TRUE);
        wp_enqueue_style('custom_css_daterangepicker',"{$ss_url}/admin-metabox/css/ui.daterangepicker.css");
        wp_enqueue_style('custom_css_jquery_ui',"{$ss_url}/admin-metabox/css/redmond/jquery-ui-1.7.1.custom.css");
    }
   }
?> 
share|improve this question
2  
@NetConstuctor.com: Don't be shocked, many people writing plugins learned to program so they could write the plugin and thus have very little programming background. They are scratching an itch, not following best practices. –  MikeSchinkel Sep 4 '10 at 0:45

6 Answers 6

up vote 13 down vote accepted

First, I assume you are using wp_enqueue_script() to load your scripts, right?

That said, if I understand your question then what you need is something like the following. You'll have to edit it for your details, of course, but it gives you the general framework.

We are hooking admin_init with the function load_my_script() to tests the global $pagenow for a match with the admin page edit.php, and the global $typenow to see if the post type is the one you want.

The rest are just details which you can read about here if you need to learn more:

<?php
add_action('admin_init','load_my_script');
function load_my_script() {
  global $pagenow, $typenow;
  if ($pagenow=='edit.php' && $typenow=='my-custom-type') {
    $ss_url = get_bloginfo('stylesheet_directory');
    wp_enqueue_script('jquery');
    wp_enqueue_script('my-custom-script',"{$ss_url}/js/my-custom-script.js",array('jquery'));
  }
}

UPDATE

I'm replying to your update. Unfortunately (for whatever reason) $typenow does not have a value during admin_init so you'll need to get the post_type by loading the post based on the URL parameter 'post' as you see in the follow example (I've copied the line above and line below from your example so you can see where to place it):

<?php
global $pagenow, $typenow;
if (empty($typenow) && !empty($_GET['post'])) {
  $post = get_post($_GET['post']);
  $typenow = $post->post_type;
}
if (is_admin() && $pagenow=='post-new.php' OR $pagenow=='post.php' && $typenow=='events') {

P.S. As for your other questions, please post them as new question on the site for me or others to answer. Since we are working so hard to help you, please take great care to give your title the best title you possibly can and also please write your questions as clearly and succinctly as possible with good formatting and proper English. If you'll do this it will help with the same issues recognize your question as being similar to what they need and it will make it easier on us who are answering your questions.

I ask this of you (and of all others who ask questions on WordPress Answers) as a favor in exchange for taking the time effort to answer your questions because I and the other moderators want to make WordPress Answers a tremendous resource for the community instead of yet another sloppy forum that is hard to read and hard to find answers like so many other sites on the web.

UPDATE #2

I thought you might have had an operator precedence issues in your if statement but when I tested before I didn't run into it. If it is behaving as your say then you almost certainly do so try this instead (sorry, I don't have time to test this right now to ensure for certain that it works):

<?php
add_action('admin_init','load_my_script');
function load_my_script() {
  global $pagenow, $typenow;
  if (empty($typenow) && !empty($_GET['post'])) {
    $post = get_post($_GET['post']);
    $typenow = $post->post_type;
  }
  if (is_admin() && $typenow=='events') {
    if ($pagenow=='post-new.php' OR $pagenow=='post.php') { 
      $ss_url = get_bloginfo('stylesheet_directory');
      wp_enqueue_script('jquery');
      wp_enqueue_script('my-custom-script',"{$ss_url}/js/my-custom-script.js",array('jquery'));
    }
  }
}
share|improve this answer
    
hi mike... see my comment below... sorry, i posted in the wrong box –  NetConstructor.com Sep 3 '10 at 22:15
    
@NetConstuctor.com: Please do not provide clarifications to your question in the place designed for answers. I've moved the content you put into an answer into your question and am voting to close that answer. –  MikeSchinkel Sep 4 '10 at 0:43
    
Hi Mike... your code works perfectly except for one issue... When you are on the admin page where you can add a new post or new page (I am talking about the default post/page) the javascript code which should only be loaded for the custom post type DOES get loaded. Other than this issue it seems to be working perfectly and is only loading the javascript on the post types specified. Do you have any modification you can suggest? –  NetConstructor.com Sep 6 '10 at 0:17
    
Sorry Mike - My initial assumption was actually incorrect. It seems that the code you provided IS included the javascript on other post types I have as well. I have gone and included the script exactly like you have suggested. Could you please review this once again? –  NetConstructor.com Sep 6 '10 at 0:22
1  
OK... So after reviewing this even further I have found out that Mike's code is indeed working correctly everywhere except when you create a "NEW" post. From what i am seeing here the javascript is incorrectly being included when you create a NEW PAGE, NEW POST for the default wordpress pages/posts as well as any custom post type you might have. The code IS working (meaing the javascript is not being included) when you EDIT an existing post or page which is either a default wordpress post or page or a custom post type. Can someone provide a suggested modification to fix this issue? –  NetConstructor.com Sep 6 '10 at 0:38

I thought I would add some code here that solved a related problem of mine. In my case I am trying to get JavaScript and css to load only on Pages and Posts and (edit and create) and no where else.

I had found a workable solution using basename( $_SERVER[ 'SCRIPT_FILENAME' ] ) to determine where on the backend I was. I was concerned though as the availability of $_SERVER[ 'SCRIPT_FILENAME' ] might vary server to server (anyone know how likely it is for $_SERVER[ 'SCRIPT_FILENAME' ] to not be available on a server?)

Then I came across this question and MikeSchinkel answer. With a little modification I made it work for me except for one thing. It seems that for whatever reason when a new post is created via "Add New" it doesn't work.

With the following tweaks I did get it to work and I am sharing it here in the hopes of helping others and of improving it.

add_action( 'admin_init','imp_add_admin_scripts' );

function imp_add_admin_scripts() {

 $urljs = get_bloginfo( 'template_directory' ).IMP_JS;
 $urlcss =get_bloginfo( 'template_directory' ).IMP_STYLES;

 // Register our scripts
 wp_register_script('imp_jquerytools', $urljs.'jquery/imp_tabs_jquery.tools.min.js' );
 wp_register_style( 'rpanel-css', $urlcss.'impoweradmin.css' );


 global $pagenow, $typenow;
 if ( empty( $typenow ) && !empty( $_GET['post'] ) ) {
  $post = get_post( $_GET['post'] );
  $typenow = $post->post_type;
 } elseif ( empty( $typenow ) && ( $pagenow == 'post-new.php' ) ){ 
  $typenow = 'post';
 }

 if ( is_admin() && ( ( $typenow == 'page') || ( $typenow == 'post') ) ){

  if ( $pagenow == 'post-new.php' OR $pagenow == 'post.php' ) {

   wp_enqueue_script( 'imp_jquerytools' );
   wp_enqueue_style( 'rpanel-css' );

  }
 }
}

Next I am trying to limit some scripts to my theme options page, which can't be done based on $pagenow as the the url that comes up is admin.php?page=themeoptions and I don't want the scripts on every admin.php page, only on that specific page (my theme options page)

Anyone know how this might best be done?

And to answer my own question:

if( is_admin() && ( $_GET['page'] == 'themeoptions' ) ){
  wp_enqueue_script( 'my-script' );

 }
share|improve this answer

I created a version that does not use the $typenow variable:

function isPostEditPage($strCheckType="")
{
    //This function will test for a post type and return true if it is the edit page for this type
    //an empty value means checking for native (original, not custom) post type
    $strCheckType=$strCheckType==""?"post":$strCheckType;
    $blnReturn=false;
    if(is_Admin())  
    {
        $strPage=basename($_SERVER['SCRIPT_FILENAME']);
        switch($strPage)
        {
            case "post.php":
                if(isset($_GET["post"]))
                {
                    $intPostID=$_GET["post"];
                    $strThisPostType=get_post_type($intPostID);
                    if($strCheckType==$strThisPostType)
                    {
                        $blnReturn=true;
                    }
                }
            break;
            case "post-new.php":
                $strThisPostType="post";
                if(isset($_GET["post_type"]))
                {
                    $strThisPostType=$_GET["post_type"];
                }
                if($strCheckType==$strThisPostType)
                {
                    $blnReturn=true;
                }

            break;
        }
    }
    return $blnReturn;
}
share|improve this answer
    
The globals won't change, so they're safe to use. Furthermore there are hooks that are specific to those pages, so you don't need that function and that effort. Last but not least: You're checking strings non-strict and also non-yoda-style, therefore they could fail. Also relying on $_GET only could fail. Anyway: Welcome to WPSE. –  kaiser Feb 20 '12 at 15:29

What about:

add_action( 'admin_init', 'scripts_admin' );

function scripts_admin($hook){

    global $typenow;
    if (empty($typenow) && !empty($_GET['post'])) {
         $post = get_post($_GET['post']);
             $typenow = $post->post_type;
     }
     if( 'post.php' != $hook && 'CUSTOMPOSTTYPE' != $typenow)
        return;

        wp_enqueue_script( 'google-api','http://maps.googleapis.com/maps/api/js?key=AIzaSyCD5TwT3vXLfYEv9WD-kOcEg7YQLcncsls&sensor=true', array( 'jquery' ) );


}
share|improve this answer

Per Justin Tadlock, you should hook into admin_enqueue_scripts as opposed to wp_enqueue_scripts for plugins or admin only scripts:

http://justintadlock.com/archives/2011/07/12/how-to-load-javascript-in-the-wordpress-admin

add_action('admin_enqueue_scripts','load_admin_datapicker_script');
share|improve this answer

I know the question has been answered. I think this is a simpler solution.

<?php
add_action( 'admin_enqueue_scripts', 'load_admin_datapicker_script' );

function load_admin_datapicker_script() {

    $current_screen = get_current_screen();

    if ( $current_screen->post_type === 'events' )  {
        $ss_url = get_bloginfo('stylesheet_directory');
        wp_enqueue_script('jquery');
        wp_enqueue_script('custom_js_jquery_ui',"{$ss_url}/admin-metabox/js/jquery-ui-1.7.1.custom.min.js",array('jquery'));
        wp_enqueue_script('custom_js_daterangepicker',"{$ss_url}/admin-metabox/js/daterangepicker.jQuery.js",array('jquery'));
        wp_enqueue_script('custom_js_custom',"{$ss_url}/admin-metabox/js/custom.js",array('jquery'),NULL,TRUE);
        wp_enqueue_style('custom_css_daterangepicker',"{$ss_url}/admin-metabox/css/ui.daterangepicker.css");
        wp_enqueue_style('custom_css_jquery_ui',"{$ss_url}/admin-metabox/css/redmond/jquery-ui-1.7.1.custom.css");
    }

}
?> 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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