douya5331 2019-02-18 20:22
浏览 72
已采纳

在自定义RSS提要中仅打印帖子的父类别

I'm trying to print only the parent category for each post and a permalink to that category within a custom Wordpress RSS feed.

Using <?php the_category_rss(); ?> prints all categories for a post (parent and child categories) like this:

<category><![CDATA[Category 1]]></category>
<category><![CDATA[Category 2]]></category>
<category><![CDATA[Category 3]]></category>

I'd like to print only the parent categories for a post rather than parent and child categories.

I'm also looking for the proper way to print the parent category's permalink within the RSS feed.

I have a feeling the way to do this is a filter, but I'm not sure how to implement it. This is what I have right now, but it returns a 1 instead of the parent category name:

add_filter('the_category_rss', 'only_parent_rss_categories');

function only_parent_rss_categories( $allparents ) {

    $categories = get_the_category();
    $category = $category->category_parent == 0;

    $allparents= esc_html("<category><![CDATA[{$category}]]></category>");

    return $allparents;
}
  • 写回答

1条回答 默认 最新

  • dstbp22002 2019-02-18 22:56
    关注

    I'm still interested in hearing how this can be accomplished using the Wordpress function the_category_rss(), but I did find another way to do this:

    <?php $parentsonly = ""; 
      // loop through categories
      foreach((get_the_category()) as $category) {
        // exclude child categories
        if ($category->category_parent == 0) {
          $parentsonly = '<category domain="' . get_category_link($category->cat_ID) . '">' . $category->name . '</category>'; 
        } 
      }
    echo $parentsonly; ?>
    

    This returns each parent category in the proper RSS validated format, using <category> and domain for the category URL:

    <category domain="http://www.yourdomain.com/category-archive/">My Category</category>

    Hope this helps someone else!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站