WordPress slug without custom post type slug

2019-06-28 03:07发布

I have register custom post type with following code:

register_post_type(
         array(
            'labels'            => // array of labels,
            'public'            => true,
            'publicly_queryable'=> true,
            'show_ui'           => false,
            'map_meta_cap'      => true,
            'show_in_menu'      => false, 
            'query_var'         => true,
            'rewrite'           => array( 'slug' => 'movie' ),
            'capability_type'   => 'post',
            'has_archive'       => false,
            'exclude_from_search' => true,
            'supports'          => array('title'),
        )
);

The issue is that, the URL become for this post like:

http://yourdomain.com/movie/post_slug/

But, I need like:

http://yourdomain.com/post_slug/

Is there any way to remove post type slug "movie" from URL, like posts and pages display at front-end by default?

Thanks

4条回答
该账号已被封号
2楼-- · 2019-06-28 03:17

You must register your post type movie in init.

register_post_type('movie', $args);

To replace the movie from post link use the below code.

function remove_my_post_type($post_link, $post, $leavename) {

    if ($post->post_type != 'movie' || $post->post_status != 'publish') {
        return $post_link;
    }

    $post_link = str_replace('/' . $post->post_type . '/', '/', $post_link);
    return $post_link;
}

add_filter('post_type_link', 'remove_my_post_type', 10, 3);

After that you can set your post type shold be like a default post or page.

function set_my_post($query) {

    if(isset($query->query['post_type'])){
        return;
    }

    if (!empty($query->query['name'])) {
        $query->set('post_type', array('post', 'movie', 'page'));
    }
}

add_action('pre_get_posts', 'set_my_post');
查看更多
来,给爷笑一个
3楼-- · 2019-06-28 03:29

Have you tried:

'with_front' => bool Should the permalink structure be prepended with the front base. (example: if your permalink structure is /blog/, then your links will be: false->/news/, true->/blog/news/). Defaults to true

https://codex.wordpress.org/Function_Reference/register_post_type

查看更多
smile是对你的礼貌
4楼-- · 2019-06-28 03:38

I do not think there is straight forward solution this. If you need this so badly you can use Custom Rewrite For Post Slug

查看更多
ゆ 、 Hurt°
5楼-- · 2019-06-28 03:42

It's simple: set 'rewrite'-> true in your args array.

查看更多
登录 后发表回答