特定类别中的帖子的自定义固定链接结构

时间:2020-02-16 作者:MaksimL

您好,我正在尝试重写一个特定类别中帖子的permalink结构,该结构应为类别名称-作者名称-帖子标题当我使用下面的代码时,URL中没有作者名称,请告诉我哪里错了。

add_filter( \'post_link\', \'custom_permalink\', \'author_link\', 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 == "Tips" ) {
    $cat_name = strtolower($category[0]->cat_name);
    $author_nickname = get_user_meta( $author_id, \'nickname\', true );
    $permalink = trailingslashit( home_url(\'/\'. $cat_name . \'/\' . 
$author_nickname . \'/\' . $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 ) && \'tips\' === $slug ) {
    $link = home_url( user_trailingslashit( \'/tips/\', \'category\' ) );
}
return $link;
}

add_action( \'init\', \'custom_rewrite_rules\' );
function custom_rewrite_rules() {
add_rewrite_rule(
    \'tips(?:/page/?([0-9]{1,})|)/?$\',
    \'index.php?category_name=tips&paged=$matches[1]\',
    \'top\' // The rule position; either \'top\' or \'bottom\' (default).
);

add_rewrite_rule(
\'tips/\\d+/([^/]+)(?:/([0-9]+))?/?$\', // <- here, add the \\d+/
\'index.php?category_name=tips&name=$matches[1]&page=$matches[2]\',
\'top\'
);
}

1 个回复
SO网友:MaksimL

此代码对我很有用:

 add_filter( \'post_link\', \'custom_permalink\', \'author_link\', 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 == "Tips" ) {
    $cat_name = strtolower($category[0]->cat_name);
    $authordata = get_userdata( $post->post_author );
        $author     = $authordata->user_nicename;
    $permalink = trailingslashit( home_url(\'/\'. $cat_name . \'/\' . $author . \'/\' .          
$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 ) && \'tips\' === $slug ) {
    $link = home_url( user_trailingslashit( \'/tips/\', \'category\' ) );
}
return $link;
}

add_action( \'init\', \'custom_rewrite_rules\' );
function custom_rewrite_rules() {
add_rewrite_rule(
    \'tips(?:/page/?([0-9]{1,})|)/?$\',
    \'index.php?category_name=tips&paged=$matches[1]\',
    \'top\' // The rule position; either \'top\' or \'bottom\' (default).
);

add_rewrite_rule(
\'tips/\\d+/([^/]+)(?:/([0-9]+))?/?$\', // <- here, add the \\d+/
\'index.php?category_name=tips&name=$matches[1]&page=$matches[2]\',
\'top\'
);
}

相关推荐

Problem with permalinks

我已经更改了类别的基本名称,现在它是“博客”,工作正常。但当我通过/blog/%category%/%postname%/更改结构时。显示404。如果我删除结构中的blog,它会再次工作,但我想使用blog word。问题出在哪里?非常感谢。