wp_old_slug_redirect()WP 2.1.0

Redirect old slugs to the correct permalink.

Attempts to find the current slug from the past slugs.

1 time — 0.000717 sec (slow) | 50000 times — 21.05 sec (slow) | PHP 7.2.5, WP 4.9.8

Return

null. Nothing (null).

Usage

wp_old_slug_redirect();

Examples

0

#1 Disable redirection from old slugs (post_names)

By default, when visiting each individual non-hierarchical post, WP makes a query to the database and checks all _wp_old_slug meta-fields of all posts to see if there is a shortcut from the current query. If such a meta-field is found, the current request is considered as the old URL of the post, so a redirect to the new URL of the posts is made.

If you don't need this behavior (not recommended), you can disable such redirections (checks) like so:

remove_action( 'template_redirect', 'wp_old_slug_redirect' );

For the query, see function _find_post_by_old_slug().

Changelog

Since 2.1.0 Introduced.

wp_old_slug_redirect() code WP 6.5.2

function wp_old_slug_redirect() {
	if ( is_404() && '' !== get_query_var( 'name' ) ) {
		// Guess the current post type based on the query vars.
		if ( get_query_var( 'post_type' ) ) {
			$post_type = get_query_var( 'post_type' );
		} elseif ( get_query_var( 'attachment' ) ) {
			$post_type = 'attachment';
		} elseif ( get_query_var( 'pagename' ) ) {
			$post_type = 'page';
		} else {
			$post_type = 'post';
		}

		if ( is_array( $post_type ) ) {
			if ( count( $post_type ) > 1 ) {
				return;
			}
			$post_type = reset( $post_type );
		}

		// Do not attempt redirect for hierarchical post types.
		if ( is_post_type_hierarchical( $post_type ) ) {
			return;
		}

		$id = _find_post_by_old_slug( $post_type );

		if ( ! $id ) {
			$id = _find_post_by_old_date( $post_type );
		}

		/**
		 * Filters the old slug redirect post ID.
		 *
		 * @since 4.9.3
		 *
		 * @param int $id The redirect post ID.
		 */
		$id = apply_filters( 'old_slug_redirect_post_id', $id );

		if ( ! $id ) {
			return;
		}

		$link = get_permalink( $id );

		if ( get_query_var( 'paged' ) > 1 ) {
			$link = user_trailingslashit( trailingslashit( $link ) . 'page/' . get_query_var( 'paged' ) );
		} elseif ( is_embed() ) {
			$link = user_trailingslashit( trailingslashit( $link ) . 'embed' );
		}

		/**
		 * Filters the old slug redirect URL.
		 *
		 * @since 4.4.0
		 *
		 * @param string $link The redirect URL.
		 */
		$link = apply_filters( 'old_slug_redirect_url', $link );

		if ( ! $link ) {
			return;
		}

		wp_redirect( $link, 301 ); // Permanent redirect.
		exit;
	}
}