_find_post_by_old_slug()WP 4.9.3

Find the post ID for redirecting an old slug.

This is an internal function for using it by WP core itself. It's not recommended to use this function in your code.

1 time — 0.000494 sec (fast) | 50000 times — 17.66 sec (slow) | PHP 7.2.5, WP 4.9.8

No Hooks.

Return

Int. The Post ID.

Usage

_find_post_by_old_slug( $post_type );
$post_type(string) (required)
The current post type based on the query vars.

Examples

0

#1 An example from the WordPress core

See the code of function wp_old_slug_redirect().

Notes

Changelog

Since 4.9.3 Introduced.

_find_post_by_old_slug() code WP 6.1.1

function _find_post_by_old_slug( $post_type ) {
	global $wpdb;

	$query = $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND post_type = %s AND meta_key = '_wp_old_slug' AND meta_value = %s", $post_type, get_query_var( 'name' ) );

	// If year, monthnum, or day have been specified, make our query more precise
	// just in case there are multiple identical _wp_old_slug values.
	if ( get_query_var( 'year' ) ) {
		$query .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
	}
	if ( get_query_var( 'monthnum' ) ) {
		$query .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
	}
	if ( get_query_var( 'day' ) ) {
		$query .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
	}

	$key          = md5( $query );
	$last_changed = wp_cache_get_last_changed( 'posts' );
	$cache_key    = "find_post_by_old_slug:$key:$last_changed";
	$cache        = wp_cache_get( $cache_key, 'posts' );
	if ( false !== $cache ) {
		$id = $cache;
	} else {
		$id = (int) $wpdb->get_var( $query );
		wp_cache_set( $cache_key, $id, 'posts' );
	}

	return $id;
}