翻了下源码,实际的查询是由以下语句控制的:
$strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false ); if ( $strict_guess ) { $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) ); } else { $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' ); }
你可以发现,他分两种模式,如果你不通过过滤器修改查询模式的话,它默认执行的是一个LIKE模糊查询。也就是说如果你输入了一个l,那么它会匹配所有slug包含l这个字母的文章和页面。之后会返回匹配到的第一个结果。至于第一个结果是如何计算的,那个是MySQL的算法范畴了,深挖下去的话无穷无尽……
你可以通过下面这个过滤器在WordPress内置的查询方法执行之前接管整个过程:
/** * Short-circuits the redirect URL guessing for 404 requests. * * Returning a non-null value from the filter will effectively short-circuit * the URL guessing, returning the passed value instead. * * @since 5.5.0 * * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404. * Default null to continue with the URL guessing. */ $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
之前的使用插件关闭是在Google上检索的,这会翻源码的时候发现可以直接通过一个过滤器关闭:
/** * Filters whether to attempt to guess a redirect URL for a 404 request. * * Returning a false value from the filter will disable the URL guessing * and return early without performing a redirect. * * @since 5.5.0 * * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL * for a 404 request. Default true. */ if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) { return false; }