Skip to content

Instantly share code, notes, and snippets.

@contemplate
Created April 28, 2022 21:20
Show Gist options
  • Save contemplate/11737073fdc24ac79216ff86a05f9fe4 to your computer and use it in GitHub Desktop.
Save contemplate/11737073fdc24ac79216ff86a05f9fe4 to your computer and use it in GitHub Desktop.
WordPress Redirect any pages that are in draft/trash to custom url
//redirect any draft/trashed posts to custom postmeta field: redirect_url_on_draft
add_action('wp', 'custom_redirect_on_draft');
function custom_redirect_on_draft(){
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 );
$post_redirect = get_post_meta( $page_id, 'redirect_url_on_draft', true );
if(($post_status == 'trash' || $post_status == 'draft') && $post_redirect){
wp_redirect($post_redirect, 302);
die();
}
}
}
}
@contemplate
Copy link
Author

contemplate commented Apr 28, 2022

INSTRUCTIONS:
You must add a custom field to the post with the name: redirect_url_on_draft
The value must be a url.
We recommend using ACF and creating a URL field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment