While working as a developer within WordPress there will often be times that you must preserve a particular URL structure. While WordPress has built in capabilities for naming the URL slug of your custom post type, there may however come a time when you need a different URL structure for your archive vs. single post. Luckily WordPress also has great redirect capabilities built-in that can be adjusted using a PHP function. In this tutorial we will teach you how to redirect the archive of a Custom Post Type via a WordPress function.

Redirect the Archive of a Custom Post Type using a WordPress Function

In order to redirect the Archive of a Custom Post Type in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below, you will need to reference the ‘Items to Note’ below in order to adjust the code to work with your specific Custom Post Type and desired redirect.

PHP

function redirect_cpt_archive() {
    if( is_post_type_archive( 'YOUR-CUSTOM-POST-TYPE' ) ) {
        wp_redirect( home_url( 'YOUR-TRAILING-SLUG' ), 301 );
        exit();
    }
}
add_action( 'template_redirect', 'redirect_cpt_archive' );

Items to Note:

  • Change ‘YOUR-CUSTOM-POST-TYPE’ to the name of the Custom Post Type you would like to have redirected.
  • home_url()will automatically insert the home URL and only the trailing slug will be needed for ‘YOUR-TRAILING-SLUG’.
  • Change ‘YOUR- TRAILING-SLUG’ to the trailing slug you would like your Custom Post Type’s Archive to redirect to.
  • If you want to redirect to an external URL just replace home_url()with your desired URL inside of quotes; example: wp_redirect( ‘http://www.yoursite.com’, 301 );
  • If you followed the instructions correctly the Archive of your Custom Post Type will now be redirected to your desired location.

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.

Share This