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.

Is there a nice way to load a js file based on the post type being viewed?

I have a supplier which has a map on it but I only want the load the js when a single one is being viewed. I load the script in my functions.php file.

share|improve this question

2 Answers 2

up vote 0 down vote accepted

If you hook onto a later action such as template_redirect, you should be able to check the query vars to determine if your specific post type is being viewed.

add_action( 'template_redirect', 'example_callback' );

function example_callback() {
    if( is_single() && get_query_var('your-posttype') )
        wp_enqueue_script( .. your args .. );
}

Or alternatively like this...

add_action( 'template_redirect', 'example_callback' );

function example_callback() {
    if( is_single() && get_query_var('post_type') && 'your-type' == get_query_var('post_type') )
        wp_enqueue_script( .. your args .. );
}

Hope that helps.

share|improve this answer
    
that seems to have worked. thanks :D –  Alex Older Feb 24 '11 at 13:31
    
You're welcome. :) Though note, there are other actions you could also use and perform the same logic, two examples would be wp_print_scripts and wp_enqueue_scripts. –  t31os Feb 24 '11 at 13:42

you can use this code:

add_action('admin_init','load_my_script');
function load_my_script() {
  global $typenow;
  if (empty($typenow) && !empty($_GET['post'])) {
    $post = get_post($_GET['post']);
    $typenow = $post->post_type;
  }
  if (!is_admin() && is_single() && $typenow=='your post type') {
    //load your script here
  }
}
share|improve this answer
    
Nope, doesn't work –  Alex Older Feb 24 '11 at 10:31
    
@Alex - care to explain what doesnt work? what does? is it on the frontend or backend? –  Bainternet Feb 24 '11 at 10:36
    
It's in the themes functions file which needs to sort the front end out. Getting the post doesn't return anything: $post = get_post($_GET['post']); –  Alex Older Feb 24 '11 at 10:44

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.