我的自定义结构永久链接设置如下所示,类别库设置为.
/%category%/%postname%/
我当前的网址结构是:
http://example.com/aaa/slug
http://example.com/bbb/slug
http://example.com/ccc/slug
http://example.com/xxx/slug
有许多类别,其中之一是xxx
。我希望该特定类别的网址从http://example.com/xxx/slug
更改为http://example.com/slug
我该怎么做?我设法以所需的方式获取了URL,但它却引发了404错误。
代码如下:
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
// Get the categories for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "xxx" ) {
$permalink = trailingslashit( home_url('/'. $post->post_name .'-'. $post->ID .'/' ) );
}
return $permalink;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
// This rule will will match the post id in %postname%-%post_id% struture
$new_rules['^([^/]*)-([0-9]+)/?'] = 'index.php?p=$matches[2]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
我也尝试了这个但没有成功:
add_filter( 'post_link', 'custom_permalink', 10, 3 );
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('init','flushRules');
function custom_permalink( $permalink, $post, $leavename ) {
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "xxx" )
{
$permalink = trailingslashit( home_url('/' . $post->post_name ) );
}
return $permalink;
}
function flushRules(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function wp_insertMyRewriteRules($rules)
{
$newrules = array();
$newrules['^/(.*)$'] = 'index.php?name=$matches[1]';
return $newrules + $rules;
}
编辑:我也根据评论尝试了此操作,但是没有用。
add_filter( 'post_link', 'custom_permalink', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
// Get the category for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == "xxx" ) {
$cat_name = strtolower($category[0]->cat_name);
$permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) );
}
return $permalink;
}
add_filter( 'category_link', 'custom_category_permalink', 10, 2 );
function custom_category_permalink( $link, $cat_id ) {
$slug = get_term_field( 'slug', $cat_id, 'category' );
if ( ! is_wp_error( $slug ) && 'xxx' === $slug ) {
$link = home_url( user_trailingslashit( '/', 'category' ) );
}
return $link;
}
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'(?:/page/?([0-9]{1,})|)/?$',
'index.php?category_name=xxx&paged=$matches[1]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
add_rewrite_rule(
'/([^/]+)(?:/([0-9]+))?/?$',
'index.php?category_name=xxx&name=$matches[1]&page=$matches[2]',
'top' // The rule position; either 'top' or 'bottom' (default).
);
}