Using a custom field value to redirect away from a 404 page

I’m moving from an old CMS to WordPress.

The old articles are saved as posts and the new WordPress permalink is %post-id%.

The old URL slug is unique and saved as a custom field for each post; the custom field name is “old_url”.

For example:

  • Post ID: 123
  • Custom field name: old_url
  • Custom field value: /servlet/Satellite?c=ArticleA_C&cid=1189064956899

I want to use the value of old_url to redirect from the old link to the new link.

So, if someone requested “domain.com/servlet/Satellite?c=ArticleA_C&cid=1189064956899”, he will be redirected to the new permalink and not receive a 404 error.

1 Answer
1

I can’t say I would recommend this on a highload system, if anything these should be 301’d in HTAccess or have their own custom table to relate to. Below is a solution which will grab the requested URL and try to find post with matching meta:

/**
 * Redirect 404s based on requested url
 *
 * @return void
 */
function wpse_226378() {
    global $wp;

    if( is_404() ) {
        $current_url = add_query_arg( $_REQUEST,$wp->request );     // Get current requested URL ( minus the domain )
        $page = get_posts( array(                                   // Get a single post that has that URL as a post meta
            'post_type'         => 'page',
            'posts_page_page'   => 1,
            'meta_key'          => 'old_url',
            'meta_value'        => sanitize_text_field( $current_url ),
            'fields'            => 'ids',
        ) );

        if( ! empty( $page ) ) {                                    // IF it's found
            wp_safe_redirect( get_permalink( $page[0] ), 301 );     // 301 redirect it
            exit;                                                   // Exit script entirely
        }
    }
}
add_action( 'template_redirect', 'wpse_226378' );

Leave a Comment