0

Add Prefix to URL of Custom Post Type

By 13th December 2018Blog

While you can use a plugin to accomplish this, I always prefer to code this manually without the need for a plugin.

To explain what we’re trying to achieve here, usually, creating a CPT (Custom Post Type) just adds this onto the site domain or where WP is installed. So normally, the URL would look like this:

http://mydomain.com/directory/post-name-here

But what we’re looking to achieve is adding a prefix before the CPT:

http://mydomain.com/MY-PREFIX/directory/post-name-here

In this example, I have a custom post type called ‘directory’ and want to add a prefix to this. Here’s how we do it.

1. Firstly, lets register our custom post type:

function pro_register_directory() {
$labels = array(
"name" => __( "Directory", "custom-post-type-pro" ),
"singular_name" => __( "Directory", "custom-post-type-pro" ),
);
$args = array(
"label" => __( "Directory", "custom-post-type-pro" ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"delete_with_user" => false,
"show_in_rest" => true,
"rest_base" => "",
"rest_controller_class" => "WP_REST_Posts_Controller",
"has_archive" => false,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "/MY-PREFIX/%directory%", "with_front" => true ),
"query_var" => true,
"menu_position" => 5,
"menu_icon" => "dashicons-feedback",
"supports" => array( "title", "editor", "thumbnail" ),
);
register_post_type( "directory", $args );
}
add_action( 'init', 'pro_register_my_cpts_graduate_directory' );

Above, the line we’ve modified from the standard code is on the rewrite line (obviously change MY-PREFIX with your prefix):

"rewrite" => array( "slug" => "/MY-PREFIX/%directory%", "with_front" => true ),

Now thats registered, we need to state what happens at %directory% (we want it to add in the normal post structure after that):

function pro_course_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
$terms = wp_get_object_terms( $post->ID, 'directory' );
if( $terms ){
return str_replace( '%directory%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'pro_course_post_link', 1, 3 );
Phil

Phil

I'm a Wordpress web developer and website designer based in Cheshire, UK. I specialise in Wordpress, Responsive design and website conversion. | Twitter | Linkedin

Leave a Reply