_find_post_by_old_slug() │ WP 4.9.3
Core function that retrieves the post ID for redirecting from the old url to the new one.
Used in the function wp_old_slug_redirect() , which performs the redirect if the post ID was found.
Algorithm:
Creates the basis for the SQL query to find the post ID by the given post type and the specified value in the meta-field with the key _wp_old_slug equal to get_query_var('name').
Adds clarifications to the query based on get_query_var('year'), get_query_var('monthnum'), get_query_var('day'), if the permalink of the post uses the year, month, day of publication.
Using $wpdb->get_var() makes the query and returns the post ID.
Internal function — this function is designed to be used by the kernel itself. It is 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.
Returns
int. post ID.
Usage
_find_post_by_old_slug( $post_type );
$post_type(string) (required)
The current post type based on query variables.
Examples
#1 An example from the WordPress core
See the code of function wp_old_slug_redirect() .
Notes Changelog
_find_post_by_old_slug() find post by old slug code
WP 7.1.2
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";
$cache = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
if ( false !== $cache ) {
$id = $cache;
} else {
$id = (int) $wpdb->get_var( $query );
wp_cache_set_salted( $cache_key, $id, 'post-queries', $last_changed );
}
return $id;
}