最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

permalinks - Removing parent slug from URL on custom post type

programmeradmin0浏览0评论

As the title states, I'd like to remove parent slugs from URLs for a particular post type: services.

Something that would change this:




etc

To something like this:




etc

I'd rather not use an additional plugins to accomplish this. I'm currently delivering the CPT via a plugin, which also registers a custom taxonomy.

As the title states, I'd like to remove parent slugs from URLs for a particular post type: services.

Something that would change this:

http://demo/parent-service/child-service-1
http://demo/grand-parent-service/parent-service/child-service-2
http://demo/great-grand-parent-service/grand-parent-service/parent-service/child-service-3
etc

To something like this:

http://demo/child-service-1
http://demo/child-service-2
http://demo/child-service-3
etc

I'd rather not use an additional plugins to accomplish this. I'm currently delivering the CPT via a plugin, which also registers a custom taxonomy.

Share Improve this question asked May 28, 2013 at 22:26 NW TechNW Tech 7177 silver badges29 bronze badges 2
  • Does your custom post type need to be hierarchical? If not, set that to false and the URLs won't be hierarchical – Matthew Boynes Commented May 28, 2013 at 22:35
  • yes, they do need to be hierarchical. this is mainly for archivial pages – NW Tech Commented May 28, 2013 at 22:37
Add a comment  | 

1 Answer 1

Reset to default 4

In a quick test, I was surprised to find that this works out of the box. That is, the canonical URI for a child post still has the parent in the path, but the child post works just as well without it (doesn't 404, doesn't redirect). As a result, it should just be a matter of filtering post_type_link to get this to work as you're asking! The following code should do just that:

function wpse_101072_flatten_hierarchies( $post_link, $post ) {
    if ( 'service' != $post->post_type )
        return $post_link;

    $uri = '';
    foreach ( $post->ancestors as $parent ) {
        $uri = get_post( $parent )->post_name . "/" . $uri;
    }

    return str_replace( $uri, '', $post_link );
}
add_filter( 'post_type_link', 'wpse_101072_flatten_hierarchies', 10, 2 );
发布评论

评论列表(0)

  1. 暂无评论