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.
<?php /** * 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(); endif;
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:
- Redirect to first post with a specific category
- Redirect to a random post
- Redirect to a custom landing page
Some simple modifications to the redirect could make this handy for a variety of tasks. Enjoy!