Redirect Field for Posts and Pages
Adds a "Redirect to" box to the post and page editor; when filled in, visitors who open that post are sent to the address you entered, on your site or elsewhere.
Opens WPIDE on
Code
add_action( 'add_meta_boxes', function () {
add_meta_box( 'wpide-redirect', 'Redirect to', function ( $post ) {
wp_nonce_field( 'wpide_redirect_save', 'wpide_redirect_nonce' );
echo '<label class="screen-reader-text" for="wpide-redirect-url">Redirect to</label>';
echo '<input type="url" class="widefat" id="wpide-redirect-url" name="wpide_redirect_url" placeholder="https://" value="' . esc_attr( get_post_meta( $post->ID, '_wpide_redirect_url', true ) ) . '" />';
echo '<p class="description">Visitors to this page are sent to this address. Leave empty to turn it off.</p>';
}, array( 'post', 'page' ), 'side', 'low' );
} );
add_action( 'save_post', function ( $post_id ) {
if ( ! isset( $_POST['wpide_redirect_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wpide_redirect_nonce'] ) ), 'wpide_redirect_save' ) ) {
return;
}
if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$url = isset( $_POST['wpide_redirect_url'] ) ? esc_url_raw( wp_unslash( $_POST['wpide_redirect_url'] ), array( 'http', 'https' ) ) : '';
if ( '' === $url ) {
delete_post_meta( $post_id, '_wpide_redirect_url' );
} else {
update_post_meta( $post_id, '_wpide_redirect_url', $url );
}
} );
add_action( 'template_redirect', function () {
if ( ! is_singular() || is_preview() ) {
return;
}
$url = get_post_meta( get_queried_object_id(), '_wpide_redirect_url', true );
if ( ! $url || untrailingslashit( $url ) === untrailingslashit( (string) get_permalink( get_queried_object_id() ) ) ) {
return;
}
wp_redirect( esc_url_raw( $url ), 301, 'WordPress' ); // phpcs:ignore WordPress.Security.SafeRedirect -- the editor chose this address.
exit;
} );
Notes
Uses a permanent (301) redirect. Clear the field to switch it off. Only users who can edit the post can set it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.