Home > front end >  How to redirect from category and shop pages to homepage in WooCommerce?
How to redirect from category and shop pages to homepage in WooCommerce?

Time:09-29

I want to hide any category pages

and the main shop page

So I need to redirect from category links and shop page to the root of the website

I use the code below for this, but it does more or less the opposite. any advice?

add_action( 'template_redirect', 'redirect_to_shop');
function redirect_to_shop() {
    // Only on product category archive pages (redirect to shop)
    if ( is_product_category() ) {
        wp_redirect( wc_get_page_permalink( 'shop' ) );
        exit();
    }
}

CodePudding user response:

You can use is_shop() and home_url()

So you get:

function action_template_redirect() {
    /* is_product_category() - Returns true when viewing a product category archive.
     * is_shop() - Returns true when on the product archive page (shop).
     *
     * (redirect to home)
     */
    if ( is_product_category() || is_shop() ) {
        wp_safe_redirect( home_url() );
        exit;
    }
}
add_action( 'template_redirect', 'action_template_redirect' );

CodePudding user response:

Try this:

add_action('template_redirect', 'wc_redirect_to_shop');
function wc_redirect_to_shop() {
    // Only on product category archive pages (redirect to root)
    if (is_product_category()) {
        wp_redirect(get_site_url());
        exit();
    }

    /**
     * Redirect shop page to root
     * Second check prevent redirect loop when front page is the as same shop page
     */
    if (is_shop() && get_site_url(null, '/') != wc_get_page_permalink('shop')) {
        wp_redirect(get_site_url());
        exit();
    }
}

You can use the following functions:

  • Related