自定义文章类型固定链接可设置两形式,分别为ID和别名,个人认为使用别名的方式再加适合SEO,不过两种方式代码都已经放上。
别名固定方式
- $posttypes = array(
- 'product' => 'product',//Woocommerce产品自定义文章类型
- 'portfolio' => 'portfolio'//作品集自定义文章类型
- );
- add_filter('post_type_link', 'custom_book_link', 1, 3);
- function custom_book_link( $link, $post = 0 ){
- global $posttypes;
- if ( in_array( $post->post_type,array_keys($posttypes) ) ){
- return home_url( $posttypes[$post->post_type].'/' . $post->post_name .'.html' );
- } else {
- return $link;
- }
- }
- add_action( 'init', 'custom_book_rewrites_init' );
- function custom_book_rewrites_init(){
- global $posttypes;
- foreach( $posttypes as $k => $v ) {
- add_rewrite_rule(
- $v.'/([一-龥a-zA-Z0-9_-]+)?.html([sS]*)?$',
- 'index.php?post_type='.$k.'&name=$matches[1]',
- 'top' );
- }
- }
ID固定形式
- $posttypes = array(
- 'product' => 'product',//Woocommerce产品自定义文章类型
- 'portfolio' => 'portfolio'//作品集自定义文章类型
- );
- add_filter('post_type_link', 'custom_book_link', 1, 3);
- function custom_book_link( $link, $post = 0 ){
- global $posttypes;
- if ( in_array( $post->post_type,array_keys($posttypes) ) ){
- return home_url( $posttypes[$post->post_type].'/' . $post->ID .'.html' );
- } else {
- return $link;
- }
- }
- add_action( 'init', 'custom_book_rewrites_init' );
- function custom_book_rewrites_init(){
- global $posttypes;
- foreach( $posttypes as $k => $v ) {
- add_rewrite_rule(
- $v.'/([0-9]+)?.html$',
- 'index.php?post_type='.$k.'&p=$matches[1]',
- 'top' );
- }
- }
最后
将上面两段代码选择一种拷贝一下放到主题的functions.php文件中。如下图
完成之后去WordPress后台--设置--固定连接--产品固定连接--自定义base中输入【/%postname%.html/】就可以固定Woocommerce商品连接并进行伪静态了。
这种方法在现在版本已经不适用了,楼主能更新下代码吗?感谢!