0

I wish redirect my terms template to a page with the save slug (to allow the client to custom the page and use a template model for this page), this is my code

function redirect_archive_term() {
   
    $categories = get_terms( array('taxonomy' => 'chapters') );

    foreach($categories as $category) {
    
        if( is_post_type_archive( $category->slug ) ) { // like chapter-1, chapter-2 ...
            wp_redirect( home_url( '/'.$category->slug ), 301 );
            exit();
        }
    }

}
add_action( 'template_redirect', 'redirect_archive_term' );

this is doesn't work because of the condition I think, there a way to target them ?

Thanks for the help :)

1 Answer 1

0

Should be pretty straight forward. The following is untested.

Function has to fire before the header is deployed, thus the use of the wp hook.

is_tax() can fire on search or archive page, we need to filter that out, thus ! is_search() && ! is_archive().

We get the current term from get_term() and we redirect through wp_safe_redirect().

<?php

/**
 * Redirect term page to the corresponding custom slug page.
 * 
 * @see https://stackoverflow.com/questions/71266569/redirect-custom-taxonomy-terms-archive-to-page
 * 
 * @since   1.0.0
 * 
 * @param   void
 * @return  void
 */
add_action( 'wp', 'wpso_71266569' );  //hook into wp's init action hook

if ( ! function_exists( 'wpso_71266569' ) ) {
    
    function wpso_71266569() {
    
        //Let's make sure we're on a taxonomy "chapters" page:
        //Either taxonomy-{taxonomy}.php or taxonomy-{taxonomy}-{term}.php.
        if ( ! is_search() && ! is_archive() && is_tax( 'chapters' ) ) {
    
            $term = get_term( get_queried_object_id() ); //Retrieve the current term slug.
    
            wp_safe_redirect( home_url( trailingslashit( $term->slug ) ) ); //eg: Redirect to https://example.com/term_slug/.
    
        };
    
    };
    
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.