代码之家  ›  专栏  ›  技术社区  ›  aronmoshe_m

在自定义RSS源中仅打印文章的父类别

  •  0
  • aronmoshe_m  · 技术社区  · 5 年前

    我试图只打印每个帖子的父类别,并在自定义Wordpress RSS提要中永久链接到该类别。

    使用 <?php the_category_rss(); ?> 打印帖子的所有类别(父类别和子类别),如下所示:

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

    我只想打印文章的父类别,而不是父类别和子类别。

    我也在寻找在RSS提要中打印父类别的permalink的正确方法。

    1 而不是父类别名称:

    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;
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   aronmoshe_m    5 年前

    我仍然很想知道如何使用Wordpress函数来实现这一点 the_category_rss() ,但我确实找到了另一种方法:

    <?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; ?>
    

    这将使用正确的RSS验证格式返回每个父类别 <category> domain 对于类别URL:

    <category domain="http://www.yourdomain.com/category-archive/"> 我的类别 </category>

    希望这能帮助别人!