Sae*_*ani 3 url wordpress .htaccess custom-post-type
我有一个 WordPress 网站,它使用自定义模板和自定义帖子类型(例如登陆和服务)。
每个帖子类型在 url 中都有一个特定的 slug,如下所示 => ( http://example.com/landing/landing-page-name )
我想将此网址(http://example.com/landing/landing-page-name)更改为此网址(http://example.com/landing-page-name)。
事实上,我需要从网址中删除 [landing] 短语。重要的是,[登陆] 是我的帖子表中的自定义帖子类型。
我测试过以下解决方案:
==> 我已将 register_post_type() 中的重写属性中的 slug 更改为“/” --> 它破坏了所有登陆、帖子和页面 url (404)
==> 我在重写属性中添加了 'with_front' => false --> 没有任何改变
==> 我尝试使用 htaccess 中的 RewriteRule 来执行此操作 --> 它不起作用或给出太多重定向错误
我无法得到正确的结果。
以前有人解决过这个问题吗?
小智 7
首先,您需要过滤自定义帖子类型的永久链接,以便所有已发布的帖子的 URL 中都不会包含 slug:
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 );
Run Code Online (Sandbox Code Playgroud)
此时,尝试查看该链接将导致 404(找不到页面)错误。这是因为 WordPress 只知道帖子和页面可以有类似domain.com/post-name/或 的URL domain.com/page-name/。我们需要告诉它我们的自定义帖子类型的帖子也可以有像domain.com/cpt-post-name/.
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' );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13039 次 |
| 最近记录: |