Loading External Scripts in Admin but ONLY for a Specific Post Type?

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.

Read More

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");
    }
   }
?> 

Related posts

Leave a Reply

7 comments

  1. 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'));
        }
      }
    }
    
  2. 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' );
    
     }
    
  3. 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");
        }
    
    }
    ?> 
    
  4. 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;
    }
    
  5. 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' ) );
    
    
    }
    
  6. This

    $typenow does not have a value during admin_init

    is not entirely correct. It does have a value set on admin_init in most post type screens like Add New, taxonomy list, taxonomy edit and entry list, but it doesn’t have one in the “Edit YourPostType” screen.

    Also, as others pointed, the correct hook to use to add stylesheets and scripts to WP Admin is admin_enqueue_scripts. If you use this hook you don’t need to check is_admin() since it’s only fired in WP Admin and you get as parameter the current screen.
    http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts