0

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');
}
2
  • I'd say (1)
    – its_me
    Commented Jun 29, 2012 at 2:56
  • Actually it's a trick question because both gave me the white screen of death
    – AlxVallejo
    Commented Jun 29, 2012 at 3:13

1 Answer 1

4

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');
2
  • 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
    Commented Jun 29, 2012 at 12:38
  • You can use has_term for that. see edit above.
    – Milo
    Commented Jun 29, 2012 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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