Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woo Conditionals on init

I'm trying to add the title above the breadcrumbs. My questions is why WooCommerce Conditionals work better on template_redirect but don't work on init. For example:

/** Woo General Init **/
function woo_general_init() {
    echo ( is_product() ) ? 'True' : 'False';

    if( is_product() ) {
        add_action( 'woocommerce_before_main_content', 'woocommerce_template_single_title', 10 );
        add_action( 'woocommerce_before_main_content', 'woocommerce_template_single_excerpt', 11 );
    }
}
add_action( 'init', 'woo_general_init' );

Evaluates to False at the top of my document when viewing a single WooCommerce product. On the other-hand, if I change init to template_redirect the conditional outputs True:

/** Woo General Init **/
function woo_general_init() {
    echo ( is_product() ) ? 'True' : 'False';

    if( is_product() ) {
        add_action( 'woocommerce_before_main_content', 'woocommerce_template_single_title', 10 );
        add_action( 'woocommerce_before_main_content', 'woocommerce_template_single_excerpt', 11 );
    }
}
add_action( 'template_redirect', 'woo_general_init' );

Why do I get "False" when hooked into init but "True" on template_redirect? What's the best hook to run WooCommerce conditional data?

like image 702
Howdy_McGee Avatar asked Sep 16 '25 01:09

Howdy_McGee


1 Answers

The action init happens too early to know if the current page should display a page. You have to wait at least until template_redirect. Reference from "is_page() not working from within a plugin" - https://wordpress.stackexchange.com/q/115142/26523

like image 70
Domain Avatar answered Sep 17 '25 18:09

Domain