wordpress的自定义文章类型非常强大,使用也非常方便,使用自定义文章类型可以完成很多功能模块的开发,例如:论坛、问答、任务、相册等,但是在使用的时候会发现有一点问题,就是发布基于自定义文章类型的内容时,发现它的固定链接并不是按照设置中的生成的,那么如果将自定义文章类型的固定链接改为ID.html
模式呢?
将以下代码添加到functions.php
中即可
/* 修改固定链接
/* (支持多种自定义类型修改)
/* -------------------------------- */
function custom_arrays(){
// key(自定义文章类型) => value(固定连接slug)
return array(
'books' => 'book',
);
}
add_filter('post_type_link', 'custom_link', 1, 3);
function custom_link( $link, $post = 0 ){
$custom_arrays = custom_arrays();
foreach ($custom_arrays as $key => $value) {
if ( $post->post_type == $key ){
return home_url( $value.'/' . $post->ID .'.html' );
} else {
return $link;
}
}
}
add_action( 'init', 'custom_rewrites_init' );
function custom_rewrites_init(){
$custom_arrays = custom_arrays();
foreach ($custom_arrays as $key => $value) {
add_rewrite_rule(
$value.'/([0-9]+)?.html$',
'index.php?post_type='.$key.'&p=$matches[1]',
'top'
);
}
}