【问题标题】:how to show a category only if it is not empty仅当类别不为空时如何显示类别
【发布时间】:2017-01-20 07:17:54
【问题描述】:

我正在使用以下遗留代码来提取帖子类型 GENRE 并在 wordpress 站点模板文件上显示记录。

<?php
$genre_ids = get_posts('fields=ids&posts_per_page=-1&post_status=publish&post_type=genre&order=asc&orderby=title');
$choices = array(array('text' => 'Select Genre From List', 'value' => 0 ));
foreach ( $genre_ids as $genre_id ) {
    $categories[] = get_the_title( $genre_id );
}
if (!empty($categories)){
    foreach ($categories as $i=>$cat) {
        print "<li>";
        print "<a href='" . get_site_url() . "/band-search-page/?cat=$cat'>" . $cat . "</a>";
        print "</li>";
    }                       
} else {
    print "<li>";
    print "no categories";
    print "</li>";
}

脚本现在可以判断是否有任何帖子类型 GENRE 然后运行查询。但我想编辑它以检查并仅在有 GENRE 时显示 GENRE。现在,即使没有数据,查询也会显示所有类别。任何帮助将不胜感激。

【问题讨论】:

  • 你必须使用 array_filter($cat); 删除空数组元素;

标签: php wordpress for-loop custom-post-type


【解决方案1】:

请试试这个代码::

<?php

$genre_ids = get_posts('fields=ids&posts_per_page=-1&post_status=publish&post_type=genre&order=asc&orderby=title');
$choices = array(array('text' => 'Select Genre From List', 'value' => 0));
foreach ($genre_ids as $genre_id)
{
    $categories[] = get_the_title($genre_id);
}
if (!empty($categories))
{
    foreach ($categories as $i => $cat)
    {
        if (!empty($cat))
        {
            print "<li>";
            print "<a href='" . get_site_url() . "/band-search-page/?cat=$cat'>" . $cat . "</a>";
            print "</li>";
        }
    }
}
else
{
    print "<li>";
    print "no categories";
    print "</li>";
}
?>

【讨论】:

    【解决方案2】:

    尝试替换这一行:

     print "<a href='" . get_site_url() . "/band-search-page/?cat=$cat'>" . $cat .   "</a>";
    

    用这条线

     print "<a href='" . get_site_url() . "/band-search-page/?cat=$cat'>" . array_values(array_filter($cat) .   "</a>";
    

    只需添加 array_filter($cat) 即可删除空数组元素。

    【讨论】:

    • @HollerTrain 试试array_values(array_filter($cat));
    【解决方案3】:

    不知道我是否理解正确,但我也在一个网站上工作,我只想显示其中存储了帖子的类别名称。我刚刚使用if(category_count &gt; 0) 进行了检查。

    好吧,您可能想要设置类别并使用get_categories() 调用它,循环它然后您可以使用category-&gt;count 来检查计数。

    希望这可能会帮助...某人.. :)

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2013-06-21
      • 2023-03-12
      • 1970-01-01
      • 2015-07-02
      相关资源
      最近更新 更多