1

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.

0

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.

1
  • 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
0

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
  }
}
3
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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