Skip to content

Instantly share code, notes, and snippets.

@TimBHowe
Last active April 28, 2022 21:24
Show Gist options
  • Save TimBHowe/6674467 to your computer and use it in GitHub Desktop.
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
<?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();
}
}
}
}
@TimBHowe
Copy link
Author

TimBHowe commented May 7, 2015

Updated to a 302 as if a once published page does come back it it used the correct header response.

@pe-pe80
Copy link

pe-pe80 commented Dec 11, 2019

Hi! Thank you for the sample code! I noticed a problem with custom posts. Hook 'template_redirect' is called too late. Example:

  1. Type: site.com/courses/java
  2. Redirect 301: site.com/?post_type=course&p=28871‎ (some magic from wordpress)
  3. Redirect 302: site.com (redirect from your example)

I had to apply this hook:
add_action('wp', 'trash_redirect');

@dani-snippets
Copy link

Thx for sharing this snippet - it works fine. I did use it with applying the addition at the comments from pe-pe80.

@TimBHowe
Copy link
Author

Updated to apply the hook on add_action('wp', 'trash_redirect'); over add_action('template_redirect', 'trash_redirect'); to work with custom post type

@contemplate
Copy link

@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