To set a custom permalink structure for custom post types in WordPress, you can use the rewrite argument in the register_post_type() function. This argument allows you to specify a custom URL structure for your custom post type.

Here is an example of how you can set a custom permalink structure for a custom post type called “book”:

function my_custom_post_type() {
   $args = array(
      'labels' => array(
         'name' => 'Books',
         'singular_name' => 'Book',
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array(
         'slug' => 'books',
      ),
   );
   register_post_type( 'book', $args );
}
add_action( 'init', 'my_custom_post_type' );

This will set the permalink structure for your custom post type to example.com/books/{book_name}. You can customize the slug argument to set a different permalink structure for your custom post type.

You can also use the post_type_link filter to customize the permalink structure further. For example, you can add a custom taxonomy to your custom post type’s permalink structure like this:

function my_custom_post_type_link( $link, $post ) {
   if ( $post->post_type === 'book' ) {
      $terms = get_the_terms( $post->ID, 'book_category' );
      if ( $terms ) {
         return str_replace( '%book_category%', array_pop( $terms )->slug, $link );
      }
   }
   return $link;
}
add_filter( 'post_type_link', 'my_custom_post_type_link', 10, 2 );

This will add the slug of the first term in the book_category taxonomy to the permalink structure, resulting in a permalink structure like example.com/books/{book_category}/{book_name}.

I hope this helps! Let me know if you have any questions.

(Visited 16 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window