問題描述
我想在自定義帖子型別中將自定義欄位新增到位於 http://example.com/feed/?post_type=my_custom_post_type 的帖子型別的 RSS Feed
我已經看到有關為常規 Feed 進行此操作的資訊,但沒有如何重寫自定義帖子型別 Feed 。
我需要新增 10-15 個專案到飼料 (第 1 行動,第 2 行動,第 3 行動,價格,購買連結…)
最佳解決方案
function add_custom_fields_to_rss() {
if(get_post_type() == 'my_custom_post_type' && $my_meta_value = get_post_meta(get_the_ID(), 'my_meta_key', true)) {
?>
<my_meta_value><?php echo $my_meta_value ?></my_meta_value>
<?php
}
}
add_action('rss2_item', 'add_custom_fields_to_rss');
您應該可以替換您需要新增到 Feed 中的任何其他元值。
次佳解決方案
嗨 @curtismchale:
捎帶 @ prettyboymp 的優秀答案,隨著我的旋轉,這裡是你可以做多個自定義欄位 (我做了 3,你可以做更多):
add_action('rss2_item', 'yoursite_rss2_item');
function yoursite_rss2_item() {
if (get_post_type()=='my_custom_post_type') {
$fields = array( 'field1', 'field2', 'field3' );
$post_id = get_the_ID();
foreach($fields as $field)
if ($value = get_post_meta($post_id,$field,true))
echo "<{$field}>{$value}</{$field}>n";
}
}
附:一定要給 @prettyboymp 道具,因為我在回答之前不知道該怎麼做。我只是回答,因為我不知道他回來之前會有多長時間,所以我決定在同一時間給你一個答案。
第三種解決方案
謝謝你這個優秀的資訊。
我想擴充套件其他兩個已經寫的內容… 為了驗證,你必須有一個自定義的名稱空間。以下是您如何做:
/* IN ORDER TO VALIDATE you must add namespace */
add_action('rss2_ns', 'my_rss2_ns');
function my_rss2_ns(){
echo 'xmlns:mycustomfields="'. get_bloginfo('wpurl').'"'."n";
}
然後用自定義名稱空間字首欄位名稱項在這個例子中,我已經使用了”mycustomfields” 參見下文:
/* add elements */
add_action('rss2_item', 'yoursite_rss2_item');
function yoursite_rss2_item() {
if (get_post_type()=='my_custom_post_type') {
$fields = array( 'field1', 'field2', 'field3' );
$post_id = get_the_ID();
foreach($fields as $field)
if ($value = get_post_meta($post_id,$field,true))
echo "<mycustomfields:{$field}>{$value}</mycustomfields:{$field}>n";
}
}
在一個側面註釋,你可以使用一個動作掛鉤到任何 3
rss2_ns : to add a specific namespace
add_action('rss2_ns', 'my_rss2_ns');
rss2_head : to add tags in the feed header
add_action('rss2_head', 'my_rss2_head');
rss2_item : to add tags in each feed items
add_action('rss2_item', 'my_rss2_item');
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。