如何解决带有自定义永久链接和标签的 WordPress 自定义帖子类型
我在这里找到了一些示例来编写代码。但是现在我被困住了,找不到任何解决此问题的方法:
我创建了一个自定义帖子类型和一个设置页面,用户可以在其中为此 CPT 设置自己的永久链接结构。例如用户可以设置类别、帖子ID、帖子名称等......这是第一次运行的截图:
问题是,如果帖子名称在 URL 中而不是 ID,我只能访问前端的页面。如果我使用 %post_id% 或 %postname% 其他占位符都没关系。
- 这有效:https://example.org/swipefile/test/
- 这不是:https://example.org/swipefile/5/(帖子 ID 为 5)
这是代码......在https://shibashake.com/wordpress-theme/custom-post-type-permalinks-part-2的帮助下
我也测试过添加 $wp_rewrite->flush_rules();
,但没有成功。
add_action( 'init','init_landingpage_cpt' );
function init_landingpage_cpt() {
$settings = new LP_Admin_Settings();
$post_type = 'landingpage';
$slug = $settings->get( 'slug' ); // Value: swipefile/%postname%
register_post_type( $post_type,array(
'description' => esc_html__( 'Library with landingpages.','lp_txt' ),'public' => true,'publicly_queryable' => true,'query_var' => true,'show_ui' => true,'show_in_menu' => 'landingapge-lib','rewrite' => array(
'slug' => $slug,'with_front' => false,),'capability_type' => 'page','has_archive' => true,'hierarchical' => true,'menu_position' => null,'supports' => array( 'title','editor','thumbnail','excerpt' ),'labels' => array(
'name' => esc_html__( 'Landingpages','singular_name' => esc_html__( 'Landingpage','menu_name' => esc_html__( 'Landingpages','name_admin_bar' => esc_html__( 'Landingpages','add_new' => esc_html__( 'Add new','add_new_item' => esc_html__( 'Add new landingpage','new_item' => esc_html__( 'New landingpage','edit_item' => esc_html__( 'Edit landingpage','view_item' => esc_html__( 'View landingpage','all_items' => esc_html__( 'Landingpages','search_items' => esc_html__( 'Search landingpages','parent_item_colon' => esc_html__( 'Parent landingpages:','not_found' => esc_html__( 'No landingpages found.','not_found_in_trash' => esc_html__( 'No landingpages found in trash.',) );
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag( "%post_id%",'([^/]+)',"{$post_type}=" );
$wp_rewrite->add_rewrite_tag( "%postname%","{$post_type}=" );
$wp_rewrite->add_permastruct( $post_type,"/{$slug}/",false );
}
add_filter( 'post_type_link','post_type_link_landingpage',10,3 );
function post_type_link_landingpage( $permalink,$post_id,$leavename ) {
$post = get_post( $post_id );
if ( ! empty( $post ) && ! empty( $permalink ) && ! in_array( $post->post_status,array( 'draft','pending','auto-draft' ) ) ) {
$search = array(
$leavename ? '' : '%postname%','%post_id%',);
$replace = array(
$post->post_name,$post->ID,);
$permalink = str_replace( $search,$replace,$permalink );
}
return $permalink;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。