Forums

wp_enqueue_script with add_action('init') (3 posts)

  1. AndySpartan
    Member
    Posted 1 year ago #

    Hi there,

    I want to enqueue some scripts and styles on the 'init' action, but only if a certain condition is met i.e the user is viewing a category page with an ID of 12. I've tried a couple of things to get it to work but am having no luck :( Below is some sample code from my functions.php file:

    function the_quote_files() {
      if(is_category(12)) {
        wp_enqueue_script(<args here);
        ... more scripts and styles ...
      }
    }
    add_action('init','the_quote_files');

    I just can't seem to get it to fire, I've also tried using get_query_var('cat') to no avail.

    My only guess as to why it isn't working is when the 'init' action is happening, no data has been processed.

    Does anyone know how I can get the scripts to load only when the user is viewing a certain category archive page?

    Thanks, Andy

  2. AndySpartan
    Member
    Posted 1 year ago #

    Ok I posted too soon, just found out how to do it if anybody else is interested..instead of hooking on to init just hook on to wp_head like so:

    add_action('wp_head','the_quote_files',0);

  3. Chip Bennett
    Member
    Posted 1 year ago #

    You should enqueue front-end scripts using the wp_print_scripts hook, rather than the wp_head hook. Otherwise, you figured it out!

    (The init hook is too soon, I think, to perform conditionals based on $post data.)

Topic Closed

This topic has been closed to new replies.

About this Topic