我有一个wordpress网站,该网站正在使用具有自定义帖子类型(例如着陆和服务)的自定义模板。
每个帖子类型在网址中都有一个特定的子句,例如=>(http://example.com/landing/landing-page-name)
我想将此URL(http://example.com/landing/landing-page-name)更改为此URL(http://example.com/landing-page-name)。
事实上,我需要从网址中删除[着陆]词组。重要的是[登陆]是我的帖子表中的自定义帖子类型。
我已经测试了以下解决方案:
==>我在register_post_type()的重写属性中将子句更改为'/'->它破坏了所有着陆,帖子和页面url(404)
==>我在重写属性中添加了'with_front'=> false->不变
==>我试图用htaccess中的RewriteRule做到这一点->它不起作用或给出太多重定向错误
我无法得到正确的结果。
有人解决过这个问题吗?
答案 0 :(得分:0)
首先,您需要过滤自定义帖子类型的永久链接,以使所有已发布的帖子的网址中都没有任何内容:
function stackoverflow_remove_cpt_slug( $post_link, $post ) {
if ( 'landing' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'stackoverflow_remove_cpt_slug', 10, 2 );
这时,尝试查看链接将导致404(找不到页面)错误。这是因为WordPress仅知道帖子和页面可以具有domain.com/post-name/
或domain.com/page-name/
之类的URL。我们需要告诉我们,自定义帖子类型的帖子也可以具有类似domain.com/cpt-post-name/
的URL。
function stackoverflow_add_cpt_post_names_to_main_query( $query ) {
// Return if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Return if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Return if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'landing' ) );
}
add_action( 'pre_get_posts', 'stackoverflow_add_cpt_post_names_to_main_query' );