搞晕晕了几天,终于把自定义类型的固定链接搞定,事情经过是这样的
先拜访前辈啊(指的是这门技术,偶人已经很老了也,沦江湖,我是前辈:),此话不细表,请接着看重点)
找到了http://www.wpdaxue.com/custom-post-type-permalink-code.html
$mytypes = array(//根据需要添加你的自定义文章类型
'type1' => 'slug1',
'type2' => 'slug2',
'type3' => 'slug3'
);
add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
function my_custom_post_type_link( $link, $post = 0 ){
global $mytypes;
if ( in_array( $post->post_type,array_keys($mytypes) ) ){
return home_url( $mytypes[$post->post_type].'/' . $post->ID .'.html' );
} else {
return $link;
}
}
add_action( 'init', 'my_custom_post_type_rewrites_init' );
function my_custom_post_type_rewrites_init(){
global $mytypes;
foreach( $mytypes as $k => $v ) {
add_rewrite_rule(
$v.'/([0-9]+)?.html$',
'index.php?post_type='.$k.'&p=$matches[1]',
'top' );
}
}
$labels = array(
'name' => __( 'Field Groups', 'mop' ),
'singular_name' => __( 'Advanced Custom Fields', 'mop' ),
'add_new' => __( 'Add New' , 'mop' ),
'add_new_item' => __( 'Add New Field Group' , 'mop' ),
'edit_item' => __( 'Edit Field Group' , 'mop' ),
'new_item' => __( 'New Field Group' , 'mop' ),
'view_item' => __('View Field Group', 'mop'),
'search_items' => __('Search Field Groups', 'mop'),
'not_found' => __('No Field Groups found', 'mop'),
'not_found_in_trash' => __('No Field Groups found in Trash', 'mop'),
);
register_post_type('share', array(
'labels' => $labels,
'public' => false,
'show_ui' => true,
'_builtin' => true,
'capability_type' => 'post',
'hierarchical' => true,
'rewrite' => true,
'query_var' => true,
'exclude_from_search'=>false,
'supports' => array( 'title'
),
'show_in_menu' => false,
));
然后改为自己定义的类型 (上面也是直接从acf拿过来的) ~~~~~~
$mytypes = array(//根据需要添加你的自定义文章类型
'share' => 'share',
'type2' => 'slug2',
'type3' => 'slug3'
);
add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
然后在前台输入 localhost/chidele/share/123.html
结果,傻眼,报404错误,找到页面。
一搜,要更新 wp的“rewrite”,可以用flush_rewrite_rules,也可进入“配置-固定链接”页面一下(不需要保存等等),就可以刷新.htaccess。
然后,那上然后,还是不行啊,404错误
多处 var_dump,原来与register_post_type有关系
'publicly_queryable' =>true,要不然index.php?post_type='.$k.'&p=$matches[1]不理你注册的类型,'_builtin' => false,否则会把你注册的类型按“内建类型”处理(按你在“设置->固定链接”设置的)
弄完这些,就大功靠成了。