问题描述

我想在自定义帖子类型中将自定义字段添加到位于 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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。