# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: redirect, posts, meta-box
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/per-post-redirect-field/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect Field for Posts and Pages" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
