How to redirect each WooCommerce product category to a different page

51 Views Asked by At

i want to redirect separately all categories to specific pages. Found this code, but this is only for one category to one page, i need to this fo 20 categories to 20 different pages.

function custom_category_template_redirect() {
    if ( is_product_category() ) {
        $category = get_queried_object();

        if ( $category->term_id == 29, ) {
            $redirect_page_id = 304; 
            wp_redirect( get_permalink( $redirect_page_id ) );
            exit();
        }
    }
}
add_action( 'template_redirect', 'custom_category_template_redirect' );

Someone to help me to resolve this case.

1

There are 1 best solutions below

0
LoicTheAztec On

It's easy… you need to set an array of product category term IDs (keys) => redirection page IDs (values) pairs, in your function, like:

add_action( 'template_redirect', 'product_category_archives_custom_redirects' );
function product_category_archives_custom_redirects() {
    if ( is_product_category() ) {
        $term_id = (string) get_queried_object_id();

        // Array of term IDs (keys) => page IDs (values)
        $data = array(
            '29' => '304',
            '31' => '305',
            '32' => '312',
        );

        if (  array_key_exists( $term_id, $data ) ) {
            wp_redirect( get_permalink( intval($data[$term_id]) ) );
            exit();
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and work.