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.

I tend to place my wp_enqueue_scripts hooks on my functions.php but this ends up piling up scripts across my site.

Which makes more sense?

1:

function load_slider(){
  global $post;
  if($post->ID == 11746){ //  Load slider on home page
    wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
    wp_enqueue_script('start-slidorion' );
  }
} 
add_action('wp_enqueue_scripts', 'load_slider');

2:

function load_slider(){
    wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
    wp_enqueue_script('start-slidorion' );
} 
global $post;
if($post->ID == 11746){ //  Load slider on home page
    add_action('wp_enqueue_scripts', 'load_slider');
}
share|improve this question
    
I'd say (1) –  its_me Jun 29 '12 at 2:56
    
Actually it's a trick question because both gave me the white screen of death –  AlxVallejo Jun 29 '12 at 3:13
add comment

1 Answer

up vote 4 down vote accepted

method two won't work because no page is loaded yet and $post isn't set when your if check runs.

with method one again $post is not yet set at that point, but this method will work if you use WordPress conditionals:

function load_slider(){
  if( is_page(11746) ){ //  Load slider on home page
    wp_register_script('start-slidorion', get_bloginfo('stylesheet_directory') . '/js/slidorion/start.js', array('slidorion', 'jquery','easing') );
    wp_enqueue_script('start-slidorion' );
  }
} 
add_action('wp_enqueue_scripts', 'load_slider');

EDIT another example using has_term:

function load_slider(){
    global $post;   
    if( has_term( 'your category', 'category', $post ) ):
        // enqueue your script
    endif;
} 
add_action('wp_enqueue_scripts', 'load_slider');
share|improve this answer
    
Thanks, I would imagine this is a common technique although there are other conditionals that depend on the page meta data. Would it be possible to use something like wp_get_object_terms to check if the page is of a certain taxonomy? –  AlxVallejo Jun 29 '12 at 12:38
    
You can use has_term for that. see edit above. –  Milo Jun 29 '12 at 14:27
    
genius, thanks! –  AlxVallejo Jun 29 '12 at 14:40
add comment

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.