2014-05-16 67 views
18

我试图创建一个自定义的固定链接结构,这将允许我完成以下操作。自定义的固定链接结构:/%自定义的固定链接类型的%/%自定义的分类%/%后名称%/

  1. 我有一个自定义职位类型,称为“项目”
  2. 我有一个名为分配到CPT“项目类别”,“项目”

我想我的永久链接结构的自定义分类看起来是这样的:

项目/分类/项目名称

/%custom-post-type%/%custom-taxonomy%/%post-name%/

我已经能够成功地使用/%category%/在永久链接中进行正常的,out-of-框中的WP帖子,但不适用于CPT。

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

感谢

+2

这个插件能解决你的问题吗? https://wordpress.org/plugins/custom-post-type-permalinks/ –

+0

我总是犹豫使用太多的插件,但我会定义尝试一下!谢谢。 –

+0

我完全同意你的看法,尽管最近我对真正基本的插件有点宽松,基本上只是从我们身上采取了一些咕噜声。希望能为你解决问题! –

回答

18

幸运的是,我刚为客户的项目做到这一点。我用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 
) 
); 

当然,一定要刷新重写规则,当你”重做。祝你好运!

+0

非常好,谢谢!我很匆忙,所以我不得不依赖一个插件(我不喜欢这样做)来快速完成它。我将在未来的项目中实现这一点! –

+1

你有没有试图让这个与子类别一起工作,或者知道我可以如何使它与子类别一起工作? – Jordan

+0

这工作;然而,'get_post_type_archive_link('projects')'在url中使用'%project_catgory%'返回,因为slug是用它定义的。 – Seed

相关问题