单个帖子类别的自定义固定链接

时间:2018-09-23 作者:De Coder

为特定帖子类别创建自定义永久链接。我得到了这个,它工作得很好,除了,它是执行重定向,而不是重写。查看URL栏时,仍应显示:example.com/new_slug/name-of-my-post 不重定向到example.com/name-of-my-post

// Changes permalink to add new path, if in this category
add_filter( \'post_link\', \'pl_custom_permalink\', 10, 3 );
function pl_custom_permalink( $permalink, $post, $leavename ) {
  global $post;
  if ( has_category( \'My Category\', $post->ID) ) {
    $permalink = trailingslashit( home_url(\'/new_slug/\'. $post->post_name . \'/\' ) );
  }
  return $permalink;
}
add_action(\'init\', \'pl_custom_rewrite_rules\');
function pl_custom_rewrite_rules( $wp_rewrite ) {
  add_rewrite_rule( \'^/new_slug/(.*)$\', \'index.php?name=$matches[1]\', \'top\' );
}
我错过了什么?

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

pl_custom_rewrite_rules() 函数,将REGEX模式更改为^new_slug/(.*)$ 例如:

add_rewrite_rule( \'^new_slug/(.*)$\', \'index.php?name=$matches[1]\', \'top\' );
因为WordPress删除了前面的/ 从请求路径(WP::$request), 所以使用^/new_slug 从不计算为true.

此外,在pl_custom_permalink() 功能,移除global $post; 因为函数已经接收到正确的post数据(即。$post) 如中所示function pl_custom_permalink( $permalink, $post, $leavename ).

我使用的完整代码,没有任何重新缩进:(在WordPress 4.9.8上进行了尝试和测试)

add_filter( \'post_link\', \'pl_custom_permalink\', 10, 3 );
function pl_custom_permalink( $permalink, $post, $leavename ) {
  if ( has_category( \'My Category\', $post->ID) ) {
    $permalink = trailingslashit( home_url(\'/new_slug/\'. $post->post_name . \'/\' ) );
  }
  return $permalink;
}
add_action(\'init\', \'pl_custom_rewrite_rules\');
function pl_custom_rewrite_rules( $wp_rewrite ) {
  add_rewrite_rule( \'^new_slug/(.*)$\', \'index.php?name=$matches[1]\', \'top\' );
}
以下是规范重定向的代码example.com/name-of-my-postexample.com/new_slug/name-of-my-post:

add_action( \'wp\', function( $wp ){
    // If it\'s a single Post and it\'s in the \'My Category\' category, redirect to
    // the canonical version. Also check if the request path doesn\'t start with
    // new_slug/ as in http://example.com/new_slug/hello-world/
    if ( ! preg_match( \'#^new_slug/#\', $wp->request ) &&
        is_singular() && in_category( \'My Category\' ) ) {
        wp_redirect( get_permalink() );
        exit;
    }
} );

结束

相关推荐