自定義文章型別固定連結可設定兩形式,分別為 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' );
- }
- }
兩種形式的固定連結程式碼也只是設定了顯示方式以及顯示的內容,ID 就顯示 0-9 其中的數字,別名就顯示所有的字元。
使用固定連結後,主題中整合的作品集文章型別在文章頁面獲取作品集分類名稱和 SEO 中獲取產品關鍵字時獲取不了,不使用固定是正常,所以 Google 找到應對方案。
1 、作品集文章頁面獲取分類名稱,新增到作品集文章頁面中
- <!--獲取作品集分類名稱-->
- <?php
- $terms = get_the_terms($post->ID, 'portfolio_field' );//portfolio_field 為作品集分類法
- if ($terms && ! is_wp_error($terms)) :
- $term_names_arr = array();
- foreach ($terms as $term) {
- $term_names_arr[] = $term->name;
- }
- $terms_name_str = join( ",", $term_names_arr);
- endif;
- ?>
- <!--獲取作品集分類名稱 end-->
2 、使用以下程式碼來呼叫分類名稱
- <?php echo $terms_name_str; ?>
透過上面的程式碼我們可以獲取 portfolio_field 的分類名稱,獲取產品關鍵字名稱也同樣適用,將上面程式碼中的 portfolio_field 修改為 product_tag 即可。
設定好自定義文章型別的固定連結,看著確實很舒服,也有利於 SEO,同時也解決設定固定連結後與其它程式碼產生的衝突。