如果帖子属于自定义分类,则更改帖子的固定链接

时间:2017-08-18 作者:BadHorsie

我的帖子都位于/blog/post-name/

我有一个称为“系列”的自定义分类法。该系列可访问/blog/series-name 显示该系列中的所有帖子。

我想做的是将系列中的所有帖子的URL更改为/blog/series-name/post-name, 但所有其他帖子都是/blog/post-name.

我怎样才能在functions.php?

1 个回复
最合适的回答,由SO网友:inarilo 整理而成

可以使用the_permalink 使用筛选和添加重写规则add_rewrite_rule 将新的永久链接重定向到标准post链接。

function mysite_modify_permalink($url) {
  global $post;
  //if taxonomy archive for Series get term
  $term = is_tax(\'Series\')?get_query_var(\'term\'):\'\';
  if(empty($term)) { //if no term was found
    //get all Series terms for current post
    $terms = get_the_terms($post, \'Series\');
    //if terms were found, take first term found
    if(!empty($terms) && is_array($terms)) $term = $terms[0]->slug;
  }
  //if term was found return a modified permalink url
  //(replace last url segment starting from \'/\' with \'/<term slug><last segment>\')
  if(!empty($term)) return preg_replace(\'#/blog(/[^/]+/?)$#\', \'/blog/\'.$term.\'$1\', $url);
  //else return original url
  else return $url;
}
add_filter(\'the_permalink\', \'mysite_modify_permalink\');

function mysite_add_rewrule() {
  //get all Series terms
  $terms = get_terms(array(\'taxonomy\' => \'Series\'));
  //if terms were found, add a rewrite rule for urls containing one of them
  if(!empty($terms) && is_array($terms)) {
    foreach($terms as $key => $term) $terms[$key] = $term->slug;
    $terms = \'(?:\' . implode(\'|\', $terms) . \')\';
    add_rewrite_rule(\'^blog/\'.$terms.\'(/[^/]+/?)$\', \'index.php?name=$matches[1]\', \'top\');
  }
}
add_action(\'init\', \'mysite_add_rewrule\');

结束

相关推荐

Pretty permalinks (again)

我正试图在我的WordPress站点中启用永久链接。但每次我尝试更改为除默认链接外的任何永久链接选项时,帖子的链接都会转到404。如果我把它改回来,它就正常工作了。我正在Ubuntu服务器14.04上使用WP 4.2.4和Apache 2.4.7。我做过的事情:我有mod_rewrite 在Apache中启用</我有选择+FollowSymLinks 和AllowOverride All 和RewriteEngine On 在Apache服务器的配置文件中</我已给予书面许可.htaccess