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