添加这种重写规则不是问题,您只需添加此代码。
/**
* Add custom rewrite rule to handle posts with and without category prefix.
*
* Remember to flush rewrite rules to apply changes.
*/
function wpse_288675_add_post_handling_without_category_prefix() {
add_rewrite_rule(\'([^/]+)(?:/([0-9]+))?/?$\', \'index.php?name=$matches[1]&page=$matches[2]\', \'top\');
}
当我将permalink结构设置为
/%category%/%postname%/
.
问题是您的内容将通过两个链接提供。具有%category%
前缀和不带。防止duplicate content
这对SEO不利,我们必须使用301代码全部重定向not uncaterogized post to url with category
以及所有uncaterogized post to url without category
. 我们可以使用下面的代码来实现这一点。
/**
* Check if displayed post have category and which category to maybe redirect user
* with 301 code to prevent duplicate content.
*/
function wpse_288675_maybe_redirect( $query ) {
// Define uncaterogized category id for convenience
if( ! defined( \'UNCATEROGIZED_CATEGORY_ID\' ) ) {
define( \'UNCATEROGIZED_CATEGORY_ID\', 1 );
}
// Do not parse request on some conditions
if( !is_admin() && $query->is_main_query() && $query->is_single() ) {
// Get post name and category from url
$slug = $query->get(\'name\');
$category_name = $query->get(\'category_name\');
$query = new WP_Query(array(
\'post_type\' => \'post\',
\'name\' => $slug,
));
if( $query->have_posts() ) {
// Get current post
$posts = $query->get_posts();
$post = current($posts);
// Get post current first category
$categories = get_the_category( $post->ID );
$category = current($categories);
// If there is no category in url redirect
// all not uncaterogized post to url with category
if( !$category_name && $category->term_id !== UNCATEROGIZED_CATEGORY_ID ) {
wp_safe_redirect( get_permalink( $post->ID ), 301 );
exit;
}
// If there is category in url redirect
// all uncaterogized post to url without category
if($category_name && $category->term_id === UNCATEROGIZED_CATEGORY_ID ) {
$url_format = \'%s/%s/\';
$url = sprintf($url_format, get_bloginfo(\'url\'), $slug);
wp_safe_redirect( $url, 301 );
exit;
}
}
}
return $query;
}
add_filter( \'pre_get_posts\', \'wpse_288675_maybe_redirect\' );
我将描述这段代码是如何在示例上工作的。我有两个帖子:
Test 1
带类别Uncaterogized
Test 2
带类别Category 1
当我到达/uncaterogized/test-1/
我正在重定向到/test-1/
.当我到达/category-1/test-2
我没有被重定向。