April 12, 2021

Remove URL prefixes from custom post types in WordPress

WordPress lets you easily configure your blog’s permalink structure in order to have custom URLs like /blog/%postname%/ or /articles/%postname%/. If you do that, you’re going to have that permalink structure even for your custom post types. That means for a Project custom post type, your URLs are going to be /blog/project/my-cool-project, which is probably not what you intend.

Getting rid of /blog/ there is quite easy, but the possible solutions to this simple problem seem quite cumbersome if you don’t look in the right place, from obscure functions to complicated URL rewrite rules.

It only takes a small tweak to the rewrite parameter of register_post_type function:

'rewrite' => array(
    'with_front' => false,
    'slug'       => 'project'
);

The complete code for registering a custom post type would be then:

// functions.php or custom plugin
$args = array(
  'label'                 => __('Project', 'theme-name'),
  'description'           => __('Projects', 'thema-name'),
  'labels'                => $labels,
  'show_in_rest' => true,
  'supports'              => array('title', 'editor', 'thumbnail', 'revisions', 'custom-fields', 'page-attributes', 'post-formats'),
  'hierarchical'          => false,
  'public'                => true,
  'show_ui'               => true,
  'show_in_menu'          => true,
  'menu_position'         => 5,
  'show_in_admin_bar'     => true,
  'show_in_nav_menus'     => true,
  'can_export'            => true,
  'has_archive'           => true,
  'exclude_from_search'   => true,
  'publicly_queryable'    => true,
  'capability_type'       => 'page',
  'rewrite' => array(
    'with_front' => false,
    'slug'       => 'project'
  )
);
register_post_type('project', $args);

Found in: What is the “with_front” rewrite key? – WordPress development Stack Exchange

Read more about register_post_type function: