How do I use the same slugs for custom post types and taxonomies in WordPress

前端 未结 2 1229
甜味超标
甜味超标 2021-02-04 19:12

I\'m new here and I need your help because I don\'t understand how to solve this.

I need to register a new custom post type \"tutorials\", because I want to have a diffe

2条回答
  •  逝去的感伤
    2021-02-04 19:59

    My answer will not solve 100% your request, but, i have been using this way on many projects and i think is the best to do in this cases.

    First of all backup your site. Then put all the code into one INIT function, this is important since you need to flush rules and it´s better if hapens at the end of the registration (i describe this at the end)

    On post type args, chage has_archive to:

    'has_archive' => 'tutorials' // This will tell wp to use the taxonomy tutorials for the post type archive
    

    And change rewrite to:

    'rewrite' => array(
            'slug' => 'tutorial', // Notice this will be the slug for single tutorial and can´t be the same as the archive slug, but has sence, since it´s ONE tutorial post, not ALL the tutorials, singlular, plural things in other words.
            'with_front' => true,
    
         ),
    

    And on the taxonomy args, change rewrite to:

    'rewrite' => array( 'slug' => 'tutorials', 'with_front' => true, 'hierarchical' => false),
    

    Then you need to run once a flush, at the end of the init function add this:

    flush_rewrite_rules();
    

    Run just once, then remove the flush_rewrite_rules from the function. This is only for rebuild the things, so you don´t leave that for ever.

    Then go to permanentlinks and save.

    Every time you made changes into taxonomies or post types slugs, you will need to flush rules and save permalinks, if not, you will recive a 404 error.

    This way you will have:

    mywebsite.com/tutorials/ (this will use the archive or taxonomy template, ej: taxonomy-tutorials.php)
    
    mywebsite.com/tutorial/post-name (notice what i describe about single slugs, template in use: single-tutorial.php)
    
    mywebsite.com/tutorials/photoshop/ (this will use the archive or taxonomy template as well and also you could have a particular template only for that term)
    

    NOTE: As i said, single post type slugs same as taxonomy archives slugs can´t be the same, will be a trouble to wp to recognize slugs for single and taxonomy archives at same time, so, the best i found is to use this method where you have a singular slug for single posts and the plural version for tax archives. At least you will not have something like "cat-tutorials" on the slug, will be better human readable and nice for SEO.

    Hope that helps.

提交回复
热议问题