根據seo優化規則我們可以對文章的標題后面帶上分類,如文章標題+分類+網站名稱,下面我主來介紹wordpress中怎么實現吧.
現象:wordpress 文章頁title標題調用所屬分類,使用single_cat_title()方法無任何內容輸出。
解析:single_cat_title():該方法只有在分類列表跟標簽頁面才能正常輸出所屬分類;
wp_title()也能在分類列表頁面title中顯示所屬分類,固只有文章頁title輸出所屬分類才需額外處理!
get_the_category()方法不帶參數,默認為獲取文章頁所屬分類的所有信息,用foreach查看這個方法返回了哪些有用信息可用,代碼如下:
- <?php
- $categories=get_the_category();
- foreach ($categories as $key => $value) {
- echo "$key => $value";
- }
- ?>
頁面報“Catchable fatal error: Object of class stdClass could not be converted to string ”運行錯誤!
從錯誤說明中可知$categories返回值中包含有class stdClass類型,我們用var_dump()函數進行輸出調試(此函數顯示關于一個或多個表達式的結構信息,包括表達式的類型與值,數組將遞歸展開值,通過縮進顯示其結構),語句為:var_dump($categories);
顯示結果為:
- array (size=1)
- 0 =>
- object(stdClass)[106]
- public 'term_id' => &int 1
- public 'name' => &string '未分類' (length=9)
- public 'slug' => &string 'uncategorized' (length=13)
- public 'term_group' => int 0
- public 'term_taxonomy_id' => int 1
- public 'taxonomy' => string 'category' (length=8)
- public 'description' => &string '' (length=0)
- public 'parent' => &int 0
- public 'count' => &int 2
- public 'object_id' => int 10
- public 'filter' => string 'raw' (length=3)
- public 'cat_ID' => &int 1
- public 'category_count' => &int 2
- public 'category_description' => &string '' (length=0)
- public 'cat_name' => &string '未分類' (length=9)
- public 'category_nicename' => &string 'uncategorized' (length=13)
- public 'category_parent' => &int 0
看了這個數組結構可知,要用foreach輸出所有有用的分類信息,上面php代碼應改為如下代碼:
- <?php
- $categories=get_the_category();
- foreach ($categories[0] as $key => $value) {
- echo "$key => $value";
- } //www.49028c.com
- ?>
加上加粗代碼部分就能解決“Catchable fatal error: Object of class stdClass could not be converted to string ”這個報錯!
到這里,文章頁title標題調用所屬分類的寫法就很明顯了,寫法如下:
- <?php
- if(is_single()){
- $categories=get_the_category();
- echo $categories[0]->cat_name;
- }
- ?>
新聞熱點
疑難解答
圖片精選