如果计数是1,则检查其是否为有效的后期段塞,如果是,则重定向如果计数是2,则检查片段是否如下/%year%/%monthnum%
如果是这样,则重定向#3可以使用基于瞬态的缓存提高性能。1。获取url让我们编写一个函数来获取url片段。它必须剥离home_url()
来自URL的部分。
function get_url_pieces() {
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), \'/\' );
$full = trim( str_replace( $home_path, \'\', add_query_arg( array() ) ), \'/\' );
$sane_array = explode( \'?\', $full );
// removing any query string
$qs = array();
if ( isset( $sane_array[ 1 ] ) ) parse_str( $sane_array[ 1 ], $qs );
$stripped = trim( $sane_array[ 0 ], \'/\\\\\' );
$pieces = ! empty( $stripped ) ? array_filter( explode( \'/\', $stripped ) ) : array();
return $pieces;
}
2。分解url片段并对其进行计数:如果计数不是1或2,则什么都不做
这部分工作流应尽可能简单地运行,\'after_setup_theme\'
是一个很好的地方,因为插件和url都可以使用,而且时间还早。add_action( \'after_setup_theme\', function() {
if ( is_admin() ) return;
$url_pieces = get_url_pieces();
if ( is_array($url_pieces) ) {
if ( count( $url_pieces ) === 1 ) {
my_post_redirect( $url_pieces );
} elseif ( in_array( count($url_pieces), array(2, 3), TRUE ) ) {
my_date_redirect( $url_pieces );
}
}
} );
3。检查url片段并在需要时应用重定向
function my_date_redirect( Array $pieces ) {
$cached = redirect_if_cached( $pieces );
// if we are here url is not cached, see redirect_if_cached() below
// let\'s check date format
if ( ! in_array( count($pieces), array( 2, 3), TRUE ) ) return;
if ( ! strlen("{$pieces[0]}") === 4 ) return;
$day = ! isset( $pieces[2] ) ? \'01\' : $pieces[2];
if ( ! checkdate ( (int)$pieces[1], (int) $day, (int) $pieces[0] ) ) return;
// that\'s a valid date
// cache and redirect
$redirect = "date/{$pieces[0]}/{$pieces[1]}";
if ( isset($pieces[2]) ) $redirect .= "/{$pieces[2]}";
$cached[ serialize($pieces) ] = $redirect;
set_transient(\'my_redirects\', $cached);
wp_safe_redirect( home_url( $redirect ), 301 );
exit();
}
用于1个URL的第二个函数function my_post_redirect( Array $pieces ) {
$cached = redirect_if_cached( $pieces );
// if we are here url is not cached, see redirect_if_cached() below
if ( ! count( $pieces ) === 1 ) return;
global $wpdb;
$query = "SELECT ID, post_name FROM {$wpdb->posts} WHERE (post_status = \'publish\'";
$query .= ( is_user_logged_in() ) ? " OR post_status = \'private\')" : \')\';
$query .= " AND post_type = \'post\' AND post_name = %s";
$post = $wpdb->get_row( $wpdb->prepare( $query, $pieces[0] ) );
if ( empty($post) ) return;
// that\'s a valid slug
// cache and redirect
$redirect = "{$post->ID}/{$pieces[0]}";
$cached[ serialize( $pieces ) ] = $redirect;
set_transient( \'my_redirects\', $cached );
wp_safe_redirect( home_url( $redirect ), 301 );
exit();
}
实现缓存function redirect_if_cached ( Array $pieces ) {
$cached = array_filter( (array) get_transient(\'my_redirects\') );
$key = serialize( $pieces );
if ( array_key_exists( $key, $cached ) ) {
wp_safe_redirect( home_url( $cached[$key] ), 301 );
exit();
}
// if url is not cached return what\'s currently cached
return $cached;
}