Support » Plugin: WooCommerce » Woocommerce conditional headers

  • Resolved adpatricia

    (@adpatricia)



    I want to load specific headers for different woocommerce product categories replacing the default get_header(shop) with custom headers. I’m using this function below but it isn’t working. Can anyone help?

    add_action( ‘init’, ‘conditional_headers’ );

    function conditional_headers() {

    if ( has_term(‘coats’, ‘product_cat’) ) {
    get_header(‘coats’);
    } elseif ( has_term(‘blue’, ‘product_cat’) ) {
    get_header(‘blue’);
    }
    }

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Support madeincosmos

    (@madeincosmos)

    Automattic Happiness Engineer

    Hi @adpatricia,

    Conditional functions like has_term only work after the posts_selection hook – which comes after init. Here you will find the order in which WordPress hooks are loaded:

    https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request

    Can you please try to hook these actions to template_redirect instead? Here is how this could look like:

    
    add_action( 'template_redirect', 'conditional_headers' );
    
    function conditional_headers() {
    
    if ( has_term('coats', 'product_cat') ) {
    get_header('coats');
    } elseif ( has_term('blue', 'product_cat') ) {
    get_header('blue');
    }
    }
    

    Please also watch out for the apostrophe character (') in the code – it seems that your text editor turned it into fancy quotes ( and ). To prevent this, you can use a plain text editor like Notepad++.

    Cheers!

    Thanks madeincosmos! This is close. It does load the custom header when it should BUT it also loads the default shop header. So it loads 2 headers (the custom one and the default one) for some reason.
    Thanks for the reminder note about the quotes…

    Plugin Support madeincosmos

    (@madeincosmos)

    Automattic Happiness Engineer

    Hmmm, what if we moved the conditional code to the header file instead? The way I see it, you could:

    1. Create a child theme to override default templates, if you haven’t already (you can do this with a plugin like Child Theme Configurator),
    2. Copy the index.php file from the parent theme to the child theme folder (usually this is the file that calls get_header(), but I’d recommend to check if your theme behaves in the same way),
    3. In the child index.php file, replace get_header(); with:

    
    if ( has_term('coats', 'product_cat') ) {
      get_header('coats');
    } elseif ( has_term('blue', 'product_cat') ) {
      get_header('blue');
    } else {
      get_header();
    }
    

    Do you think this could work for you?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Woocommerce conditional headers’ is closed to new replies.