自定義文章型別固定連結可設定兩形式,分別為 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,同時也解決設定固定連結後與其它程式碼產生的衝突。