2017-08-25 25 views
1

我正在創建函數來爲我的帖子輸出Microdata。我想使用分類標準爲meta-keywords,所以我需要將它們輸出爲以逗號分隔的文本。如何將Wordpress Taxonomy輸出爲文本,然後將它們用作元關鍵字?

我試圖遵循this question here中的解決方案,但根本沒有結果。

第一次嘗試:

echo '<meta itemprop="keywords" content="'; 
$terms = get_the_term_list($post->ID,', '); 
$terms = strip_tags($terms); 
echo $terms; 
echo '"/>'; 

第二次嘗試:

$terms = get_the_term_list($post->ID,', '); 
$terms = strip_tags($terms); 
echo '<meta itemprop="keywords" content="'; 
echo $terms; 
echo '"/>'; 

第三次嘗試:

$terms = get_the_term_list($post->ID,', '); 
$terms = strip_tags($terms); 
echo '<meta itemprop="keywords" content="'; 
$terms; 
echo '"/>'; 

所有的嘗試並沒有導致任何輸出。你可以請告知,如果有辦法達到這樣的輸出:

<meta itemprop="keywords" content="category1,category2,tag1,tag2,tag3"/> 

在此先感謝。

回答

0

你的第三個嘗試永遠不會成功,因爲你必須使用echo打印出來的條款,但你的第一次嘗試比較接近。

問題是您沒有正確使用get_the_term_list()See the Codex - 它一次只適用於一種分類標準,並且必須傳遞您希望獲取條款的分類標準名稱。

您想要獲得所有分類法的所有術語,所以首先您需要獲得所有分類法的列表,然後您可以使用該列表來獲取術語。

我也建議使用wp_get_post_terms(),因爲它可以返回沒有標籤的名稱。

$term_names = array(); // array to store all names until we're ready to use them 

// get all taxonomies for the current post 
$taxonomy_names = get_object_taxonomies($post); 

foreach ($taxonomy_names as $taxonomy){  
    // get the names of all terms in $taxonomy for the post 
    $term_list = wp_get_post_terms($post->ID, $taxonomy, array("fields" => "names")); 

    // add each term to our array 
    foreach($term_list as $term){ 
     $term_names[] = $term; 
    } 
} 

if ($term_names){ // only display the metatag if we have any terms for this page 
    // implode will join all the terms together separated by a comma 
    $keywords = implode(",", $term_names); 
    echo '<meta itemprop="keywords" content="'.$keywords .'"/>'; 
} 

我還沒有測試的代碼,所以有可能是一對夫婦的問題,但讓我知道,因爲邏輯應該爲你工作。

+0

非常感謝。我粘貼了代碼。它沒有破壞網站(所以我相信沒有錯誤?),但是當我檢查Google的「結構化數據測試工具」中的帖子時,它根本沒有顯示任何關鍵字。有沒有辦法調試代碼,因爲我不擅長PHP? –

+0

@AtefWagih調試php的最佳方式是打印出每個階段的功能。所以,我會在每一步之後執行'var_dump()',例如''var_dump($ taxonomy_names);'在調用'get_object_taxonomies'','var_dump($ term_list)'''''wp_get_post_terms'之後'等等。可以看到什麼工作和停止。我發現了這個問題,但是對於你來說,嘗試一下你是否能找到它會是一個好習慣。您可以作爲開發人員擁有的最佳技能是如何解決問題!:-)讓我知道你什麼時候找到它,我會告訴你如何解決它(或者如果你沒有找到它,我會告訴你它在哪裏)。 – FluffyKitten

+0

感謝您幫助我成爲更好的開發人員。我啓用了調試模式,並在每一步添加了'var_dump()',但我所看到的只是一個使用了不推薦使用的函數的插件。所以我會很感激你告訴我你的代碼中的問題在哪裏,所以我可以使用該函數。謝謝:) –

相關問題