Last active
April 28, 2022 21:24
-
-
Save TimBHowe/6674467 to your computer and use it in GitHub Desktop.
WordPress Redirect any pages that are in draft/trash for non login users to the home page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//redirect any draft/trashed posts | |
add_action('wp', 'trash_redirect'); | |
function trash_redirect(){ | |
if ( !current_user_can( 'edit_pages' ) ) { | |
if (is_404()){ | |
global $wp_query, $wpdb; | |
$page_id = $wpdb->get_var( $wp_query->request ); | |
$post_status = get_post_status( $page_id ); | |
if($post_status == 'trash' || $post_status == 'draft'){ | |
wp_redirect(home_url(), 302); | |
die(); | |
} | |
} | |
} | |
} |
Hi! Thank you for the sample code! I noticed a problem with custom posts. Hook 'template_redirect' is called too late. Example:
- Type: site.com/courses/java
- Redirect 301: site.com/?post_type=course&p=28871 (some magic from wordpress)
- Redirect 302: site.com (redirect from your example)
I had to apply this hook:
add_action('wp', 'trash_redirect');
Thx for sharing this snippet - it works fine. I did use it with applying the addition at the comments from pe-pe80.
Updated to apply the hook on add_action('wp', 'trash_redirect');
over add_action('template_redirect', 'trash_redirect');
to work with custom post type
@TimBHowe thanks so much for this!
I made a version that allows for redirecting to a custom url:
https://gist.github.com/contemplate/11737073fdc24ac79216ff86a05f9fe4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to a 302 as if a once published page does come back it it used the correct header response.