Skip to content

Instantly share code, notes, and snippets.

@thobroni
Created June 4, 2020 04:54
Show Gist options
  • Save thobroni/fbf25f05164299533db93ba7c89f2c83 to your computer and use it in GitHub Desktop.
Save thobroni/fbf25f05164299533db93ba7c89f2c83 to your computer and use it in GitHub Desktop.
Remove the slug from published cpt post permalinks.
<?php
/**
* Remove the slug from published post permalinks.
* Only affect to our custom post type, though.
*/
add_filter("post_type_link", "wphdlr_remove_post_type_slug", 10, 3);
function wphdlr_remove_post_type_slug($post_link, $post, $leavename)
{
if (!in_array("users", $post->post_type))
{
return $post_link;
}
$post_link = str_replace("/" . $post->post_type . "/", "/", $post_link);
return $post_link;
}
/**
* Have WordPress match postname to any of our public post types (post, page, race)
* All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
* By default, core only accounts for posts and pages where the slug is /post-name/
*
* This function remove Custom Post Type base : http://localhost/user/wprelic to http://localhost/wprelic
*/
add_action("pre_get_posts", "wphdlr_cpt_parse_request");
function wphdlr_cpt_parse_request($query)
{
/**
* Only main query.
*/
if (!$query->is_main_query())
return;
/**
* Only for our very specific rewrite rule match.
*/
if (2 != count($query->query) || !isset($query->query['page']))
return;
/**
* 'name' will be set if post permalinks are just post_name, otherwise the page rule will match.
*/
if (!empty($query->query["name"]))
{
$query->set("post_type", array("page"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment