Solution redirect url old site to new site of post on WordPress

  1. Save old post permalink to postmeta

2. Check request add redirect

add_action( 'wp', function() {
	if ( is_404() ) {
		$uri = $_SERVER['REQUEST_URI'];

		global $wpdb;

		$meta_db = $wpdb->prefix . 'postmeta';
		$sql = "SELECT * FROM $meta_db WHERE `meta_key` = 'old_permalink' AND `meta_value` LIKE '%{$uri}%';";
		$result = $wpdb->get_row($wpdb->prepare($sql), ARRAY_A);

		if ( ! empty($result) ) {
			$post_id = absint($result['post_id']);
			$link = get_the_permalink( $post_id );
			wp_safe_redirect( $link, 301 );
		}
	}
}
);

Leave a Reply

Your email address will not be published. Required fields are marked *