5

I have a category archive page at: http://mysite.com/news

It displays an archive of items from the category 'news-article'

I'd like to redirect any requests for http://mysite.com/category/news-article to http://mysite.com/news (so that the former is never directly accessible).

Is there a best practice? Should I put a 301 Redirect in my .htaccess file (or use a plugin to do the same)?

Or should I use wp_safe_redirect? If yes, which action hook should I use? As in:

add_action( 'WHICH_ACTION_HOOK??', 'adam_redirect_news' );
function adam_redirect_news () {
    if ( is_category( 'news-article' ) ) {

        wp_safe_redirect( 'http://mysite.com/news' );
        exit;
    }
}
6

I don't know for some reason, the add_filter caused error. I used the following one:

function my_page_template_redirect()
{
    if ( is_category( 'news-articles' ) ) {
        $url = site_url( '/news' );
        wp_safe_redirect( $url, 301 );
        exit();
    }
}
add_action( 'template_redirect', 'my_page_template_redirect' );
3

Thanks to @Layka above, I tweaked the code slightly and this does what I needed.

It could perhaps be any filter called around the same time - not sure.

/**
 * Redirect 'category/news-articles' category to 'News page' ( at http://www.example.com/news' )
 *
 */
add_filter('template_redirect', 'template_redirect_filter', 10, 3);
function template_redirect_filter( $url, $term, $taxonomy ) {

    if ( is_category( 'news-articles' ) ) {

        $url = site_url( '/news' );

        wp_safe_redirect( $url, 301 );

        exit;

    }

    return $url;

}
  • I think template_redirect would be the best hook in this case. I see situation where your solution can lead to strange website behaviour ... term_link hook definitely shouldn't be use to triggering URL redirection. – Marek Aug 18 '15 at 12:12
  • 1
    template_redirect is (IMO) the best hook for handling a redirect. It is usually the last hook before anything is sent to the browser, after which you could not redirect without error. Hook earlier and you may not have access to all the necessary information for logic (like checking categories). Also, best to stick to actions for redirection, not filters. Filters are intended for returning a value to the current process. Actions are for doing something (like redirection). – butlerblog Mar 18 '19 at 13:21
0
function template_category_template_redirect()
{
    if( is_category())
    {
        wp_redirect( site_url() );
        die;
    }
}
add_action( 'template_redirect','template_category_template_redirect' );
  • While I can see that this is an answer to the question, it's helpful (and often desirable) to include some explanation as to why it's the right/best answer. – butlerblog Mar 18 '19 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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