Custom post types and permalink

I’m looking for a way to solve my problem with permalinks in wordpress.

I have 3 post types: news (default), posttype1, posttype2

Read More

all 3 uses the standard category. I added 3 categories in it: cat1, cat2, cat3

What I want is this: : show all posts of « posttype1 » : show all posts of « posttype1 » that are in category « cat1 » : show the post named « post-name » in « posttype1 » that is in category « cat1 »

and apply that rule to all 3 post types… I’ve tried almost everything about rewriting rules in function.php, but can’t find any solution. And if I put /%category%/%postname%/ in permalink settings, it actually works well for the default post type, but don’t work for both custom post types: the category is not taken into account.

I’ve tried to install the Custom Post Type Permalinks plugin, but here again the category is not taken into account.

This is actually what I have in my functions.php (for posttype1)

register_post_type(‘posttype1’, array(
  'label' => __(‘Posttype1’),
  'singular_label' => __(‘Posttype1’),
  'public' => true,
  'show_ui' => true,
  'capability_type' => 'post',
  'hierarchical' => true,
  'menu_position' => 4,
  'supports' => array('title', 'editor'),
  'rewrite' => array('slug' => 'posttype1', 'with_front' => false),
  'has_archive' => true,
  'taxonomies' => array('category')

Related posts

Leave a Reply

1 comment

  1. There are 3 parts to making this work.

    Register the post type with correct rewrite slug and archive.

    We add the %category% rewrite tag to the slug so we can swap in the selected category. We also specify the archive name explicitly. I’ve omitted the rest of the register_post_type arguments here, the rest can be as-is in your own example.

    'rewrite' => array('slug' => 'posttype1/%category%', 'with_front' => false),
    'has_archive' => 'posttype1',

    Add a rewrite rule to handle post type / category archive.


    This will enable category archive views for your post type. Place both of the above in a function hooked to init.

    Filter post_type_link to swap in the category name for post permalinks.

    function wpd_custom_post_link( $post_link, $id = 0 ){
        $post = get_post($id);
        if ( is_object( $post ) && $post->post_type == 'posttype1' ){
            $terms = wp_get_object_terms( $post->ID, 'category' );
            if( $terms ){
                return str_replace ( '%category%' , $terms[0]->slug , $post_link );
        return $post_link;
    add_filter( 'post_type_link', 'wpd_custom_post_link', 1, 3 );

    Repeat the above steps for each post type you want to enable.