I'm trying to set up a redirect for drafted posts of the post type "Personnel", as we'd rather show a page with a custom message than a 404 page in this instance. I have added the following to functions.php
(adopted from this older thread) which for some reason only works for logged-in users- otherwise, the general 404 page shows. I've also tried adding the redirect to the single-personnel.php
template, but it has no effect. I'm wondering how to get this redirect working for all users (logged in or not) and/or if there's a better way to implement the redirect? Thanks for any insight here.
add_action( 'template_redirect', 'inactive_personnel_redirect', 0 );
function inactive_personnel_redirect() {
global $post;
if( ( $post->post_status == 'draft' ) && ( is_singular('personnel') ) ) {
wp_redirect( home_url() . '/about-us/inactive', 301 );
exit;
}
}
My Answer:
"post" in WordPress. Here's a code snippet that you can add to your theme's functions.php file to achieve this:
php
function redirect_draft_posts() {
global $post;
if ( $post->post_status == 'draft' && $post->post_type == 'post' ) {
wp_redirect( home_url() ); // Redirect to the home page
exit;
}
}
add_action( 'template_redirect', 'redirect_draft_posts' );
This code checks if the current post is a draft and of the post type "post", and then redirects the user to the home page. You can modify the `wp_redirect()` function to redirect to a different page if needed.
Make sure to test this code on a staging site before implementing it on your live site to ensure it works as expected.
Rate this post
4 of 5 based on 5919 votesComments