Redirect Custom Post Type Archive to First Post in WordPress

In a recent project I was working with a Custom Post Type called Videos. In this specific layout, the single video page would show the embedded YouTube video with some other arbitrary information as well as a list of all other videos available. Instead of having an archive page showing all videos, and then duplicating that layout on the single post page under the main video it seemed logical to simply redirect the user to the first post if they happen to visit the video archive page.

This simple little technique will allow you to automatically redirect users from the post archive page for a custom post type directly to the first post of that post type.

 * Redirect to first post from CPT

$args = array(
     'orderby'        => 'menu_order', 
     'post_type'      => 'YOUR-POST-TYPE', 
     'posts_per_page' => 1
$loop = query_posts($args);

if (have_posts()) :
	wp_redirect(get_permalink(), 302);exit();

This little snippet will go in the archive template for your custom post type. If you don’t have one you can create one by creating a file called archive-YOURCPT.php and placing it in the root of your theme or child theme. (Replace YOURCPT with your post type – in my case the file is archive-videos.php)

This works by querying your custom post type for a single post, and then redirecting to the permalink of that post when the page loads. A simple, effective way to point your traffic to the first post of your custom post type.

Additional Redirect Options

This technique could be modified to redirect in a variety of ways. A few ideas would be:

  1. Redirect to first post with a specific category
  2. Redirect to a random post
  3. Redirect to a custom landing page

Some simple modifications to the redirect could make this handy for a variety of tasks. Enjoy!

About Matt Whiteley

Matt has been building bespoke WordPress websites for over 10 years specializing in the Genesis Framework. He integrates Advanced Custom Fields heavily in all builds, especially with the new Gutenberg Block Editor, allowing clients to easily modify all aspects of the their website with ease.

He works with a wide variety of small businesses and agencies across the country providing development services as well as hosting and maintenance. When he isn't coding he enjoys spending time with his wife and two children, golfing and playing poker.