自定义文章类型固定链接可设置两形式,分别为 ID 和别名,笔者认为使用别名的方式再加适合 SEO,不过两种方式代码都已经放上。很多主题也会有两种或两种以上的自定义类型文章,为文章类型添加一个数组就可以,这样不论多少种自定义文章类型都适合。

自定义文章类型固定链接:别名形式

  1. $posttypes = array(
  2.     ‘product’ => ‘product’,//WooCommerce 产品自定义文章类型
  3.     ‘portfolio’ => ‘portfolio’//作品集自定义文章类型
  4. );
  5. add_filter(‘post_type_link’, ‘custom_book_link’, 1, 3);
  6. function custom_book_link( $link, $post = 0 ){
  7.     global $posttypes;
  8.     if ( in_array( $post->post_type,array_keys($posttypes) ) ){
  9.         return home_url( $posttypes[$post->post_type].’/’ . $post->post_name .’.html’ );
  10.     } else {
  11.         return $link;
  12.     }
  13. }
  14. add_action( ‘init’, ‘custom_book_rewrites_init’ );
  15. function custom_book_rewrites_init(){
  16.     global $posttypes;
  17.     foreach( $posttypes as $k => $v ) {
  18.         add_rewrite_rule(
  19.             $v.’/([一-龥 a-zA-Z0-9_-]+)?.html([sS]*)?$’,
  20.             ‘index.php?post_type=’.$k.’&name=$matches[1]’,
  21.             ‘top’ );
  22.     }
  23. }

自定义文章类型固定链接:ID 形式

  1. $posttypes = array(
  2.     ‘product’ => ‘product’,//WooCommerce 产品自定义文章类型
  3.     ‘portfolio’ => ‘portfolio’//作品集自定义文章类型
  4. );
  5. add_filter(‘post_type_link’, ‘custom_book_link’, 1, 3);
  6. function custom_book_link( $link, $post = 0 ){
  7.     global $posttypes;
  8.     if ( in_array( $post->post_type,array_keys($posttypes) ) ){
  9.         return home_url( $posttypes[$post->post_type].’/’ . $post->ID .’.html’ );
  10.     } else {
  11.         return $link;
  12.     }
  13. }
  14. add_action( ‘init’, ‘custom_book_rewrites_init’ );
  15. function custom_book_rewrites_init(){
  16.     global $posttypes;
  17.     foreach( $posttypes as $k => $v ) {
  18.         add_rewrite_rule(
  19.             $v.’/([0-9]+)?.html$’,
  20.             ‘index.php?post_type=’.$k.’&p=$matches[1]’,
  21.             ‘top’ );
  22.     }
  23. }

两种形式的固定链接代码也只是设置了显示方式以及显示的内容,ID 就显示 0-9 其中的数字,别名就显示所有的字符。

使用固定链接后,主题中集成的作品集文章类型在文章页面获取作品集分类名称和 SEO 中获取产品关键字时获取不了,不使用固定是正常,所以 Google 找到应对方案。

1 、作品集文章页面获取分类名称,添加到作品集文章页面中

  1. <!– 获取作品集分类名称–>
  2. <?php
  3. $terms = get_the_terms($post->ID, ‘portfolio_field’ );//portfolio_field 为作品集分类法
  4. if ($terms && ! is_wp_error($terms)) :
  5.     $term_names_arr = array();
  6.     foreach ($terms as $term) {
  7.         $term_names_arr[] = $term->name;
  8.     }
  9.     $terms_name_str = join( “,”, $term_names_arr);
  10. endif;
  11. ?>
  12. <!– 获取作品集分类名称 end–>

2 、使用以下代码来调用分类名称

  1. <?php echo $terms_name_str; ?>

通过上面的代码我们可以获取 portfolio_field 的分类名称,获取产品关键字名称也同样适用,将上面代码中的 portfolio_field 修改为 product_tag 即可。

设置好自定义文章类型的固定链接,看着确实很舒服,也有利于 SEO,同时也解决设置固定链接后与其它代码产生的冲突。