自定义固定链接结构:/%custom-post-type%/%custom-taxonomy%/%post-name%/

时间:2014-05-16 15:14:53

标签: wordpress permalinks

我正在尝试创建一个自定义永久链接结构,以便我完成以下操作。

  1. 我有一个名为“projects”的自定义帖子类型
  2. 我有一个名为“项目类别”的自定义分类,分配给CPT“项目”
  3. 我希望我的永久链接结构如下所示:

    项目/分类/项目名

    /%定制后类型%/%定制分类%/%名交%/

    我已经成功地在永久链接中使用/%category%/来获得正常的,开箱即用的WP帖子,但不能用于CPT。

    如何创建这样的永久链接结构会影响URL或其他页面?是否可以定义自定义永久链接结构并将其限制为单个CPT?

    由于

3 个答案:

答案 0 :(得分:25)

幸运的是,我只是必须为客户项目执行此操作。我使用this answer on the WordPress Stackexchange作为指南:

/**
 * Tell WordPress how to interpret our project URL structure
 *
 * @param array $rules Existing rewrite rules
 * @return array
 */
function so23698827_add_rewrite_rules( $rules ) {
  $new = array();
  $new['projects/([^/]+)/(.+)/?$'] = 'index.php?cpt_project=$matches[2]';
  $new['projects/(.+)/?$'] = 'index.php?cpt_project_category=$matches[1]';

  return array_merge( $new, $rules ); // Ensure our rules come first
}
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );

/**
 * Handle the '%project_category%' URL placeholder
 *
 * @param str $link The link to the post
 * @param WP_Post object $post The post object
 * @return str
 */
function so23698827_filter_post_type_link( $link, $post ) {
  if ( $post->post_type == 'cpt_project' ) {
    if ( $cats = get_the_terms( $post->ID, 'cpt_project_category' ) ) {
      $link = str_replace( '%project_category%', current( $cats )->slug, $link );
    }
  }
  return $link;
}
add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );

注册自定义帖子类型和分类时,请务必使用以下设置:

// Used for registering cpt_project custom post type
$post_type_args = array(
  'rewrite' => array(
    'slug' => 'projects/%project_category%',
    'with_front' => true
  )
);

// Some of the args being passed to register_taxonomy() for 'cpt_project_category'
$taxonomy_args = array(
  'rewrite' => array(
    'slug' => 'projects',
    'with_front' => true
  )
);

当然,确保在完成后刷新重写规则。祝你好运!

答案 1 :(得分:0)

在注册自定义帖子类型时,使用slug作为

$post_type_args = array(
  'rewrite' => array(
    'slug' => 'projects',
    'with_front' => true
  )

您可以尝试使用设置->永久链接

将该帖子设为父级,同时也创建您的链接

答案 2 :(得分:0)

由于 WordPress 近年来发生了很大变化,因此有一个新的解决方案。

// Used for registering cpt_project custom post type
$post_type_args = array(
  'rewrite' => array(
    'slug' => '/%custom-post-type%/%custom-taxonomy%/%postname%/',
    'with_front' => true
    'walk_dirs' => false
  )
);

%custom-post-type% 必须与您的自定义帖子类型的名称匹配 %custom-taxonomy% 必须与您的分类法名称匹配 WordPress 会自动创建正确的重写规则和链接

使用 'walk_dirs' => false 您可以防止 WP 创建疯狂的规则,例如只有 [^/]+/ 因为您的链接以自定义帖子类型开头

而且通常甚至不需要这种 dir walk,因为您只能访问结构中的站点或单独的分类站点。

这样你的重写规则就尽可能精确,你不需要用

来获取规则
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );

然后在它们前面加上

add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );

如接受的答案中所述。这样可以节省内存和执行时间!

希望这对任何正在寻找 WP 版本 > 5.X 的问题的人有所帮助