custom post types - Redirect a page based on last word in slug

admin2025-06-06  7

I have a couple custom post types registered = Staff, Properties

If I have a page with the slug archive-staff, how can I automatically redirect that page to the Staff CPT archive page with a php function?

This should also work for any page that starts with "archive-", automatically redirecting to the archive of any registered custom post type that matches the 2nd word of the slug.

So the custom archive-staff page would redirect to the Staff CPT archive page.

The custom archive-properties page would redirect to the Properties CPT archive page.

...and so on for for all custom post types only if their corresponding custom page exists.

I have a couple custom post types registered = Staff, Properties

If I have a page with the slug archive-staff, how can I automatically redirect that page to the Staff CPT archive page with a php function?

This should also work for any page that starts with "archive-", automatically redirecting to the archive of any registered custom post type that matches the 2nd word of the slug.

So the custom archive-staff page would redirect to the Staff CPT archive page.

The custom archive-properties page would redirect to the Properties CPT archive page.

...and so on for for all custom post types only if their corresponding custom page exists.

Share Improve this question asked Nov 2, 2018 at 18:18 Charlie WedelCharlie Wedel 233 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

There are many solutions for that..

1. .htaccess rules

You can put some redirect rules in your .htaccess file:

RewriteRule ^(.*)\-staff/$ /staff/? [L,R=301]
// some other rules

2. Using WordPress hooks

function my_redirect_function() {
    global $wp;

    if ( preg_match( '@staff/?$@', $wp->request ) ) {
        wp_redirect( get_post_type_archive_link( 'staff' ) );
        die;
    }

    // ... put other rules in here
}
add_action( 'template_redirect', 'my_redirect_function' );

3. Using Redirection plugin

You can use that plugin and define custom redirects based on regular expressions.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749206877a317257.html

最新回复(0)