Remove post type name from url from custom post type
Add the below code in your functions.php in wordpress theme and after that open settings > permalinks and save the permalinks again to refresh the urls. For eg, if you have the existing url http://yourdomain.com/services/postname this below code will convert this url to http://yourdomain.com/postname and suppose your custom post url like this http://yourdomain.com/services/postparent/postchild then it convert the url to http://yourdomain.com/postparent/postchild. Hope it help you out.
function cf_remove_cpt_slug( $post_link, $post ) {
if ( 'services' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'cf_remove_cpt_slug', 10, 2 );
function add_cpt_post_names_to_main_query( $query ) {
if ( ! $query->is_main_query() ) {
return;
}
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
//return;
}
if ( empty( $query->query['name'] ) && ($query->query['post_type']) ) {
return;
}
$query->set( 'post_type', array( 'post', 'page', 'services' ) );
}
add_action( 'pre_get_posts', 'add_cpt_post_names_to_main_query' );