【问题标题】:A-Z Index of Categories for WordpressWordpress 类别的 A-Z 索引
【发布时间】:2012-10-06 02:35:34
【问题描述】:

有没有人见过任何 wordpress 插件,它提供按字母顺序排列的类别索引,可以将您带到属于特定字母的类别页面。基本上,有一个列表:A B C D ... X Y Z 你可以点击,当你点击 A 时,你会进入一个页面,你会看到所有以字母 A 开头的类别?

我已经搜索了一个多小时,但找不到这个...我开始在 MySQL 上乱搞SELECT term_id as id, name as post_title FROM wp_terms ORDER BY name,但这也包括类别中的标签,我只想获取类别。

更新:

好的,看来我可以通过以下方式仅从 wp_term_taxonomy 中获取类别:

SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy =  'category'

然后,我可以获取该数组并在此处运行它:

SELECT term_id, name FROM wp_terms WHERE term_id IN (that-array) ORDER BY name

怎么样?如何使用我上面的内容创建一个新表?

【问题讨论】:

    标签: mysql wordpress plugins indexing categories


    【解决方案1】:

    你可以使用这个函数并传递一个字母作为参数

      function get_category_by_letter($letter){
        $args=array(
        'orderby' => 'name',
        'order' => 'ASC',
        'hide_empty' => 0);
    
        $categories=get_categories($args);
        foreach($categories as $category) {
    
        $catname = $category->name;
        $first_letter = substr(strip_tags($catname), 0 , 1); // get the first letter of the category
        if(strcasecmp($first_letter,$letter) != 0) continue; //if not the same letter then loop next NOTE: this is case insensitive comparison
        else{
          $cats[] = $category->term_id; //store category IDs in array
          //$cats[] = $category->name; uncomment this if you want to get category name
          //or you can start your process here and remove the return value  
            }
        }
     return $cats;
    }
    

    示例用法

      $cats = get_category_by_letter('A');
      var_dump($cats);
    

    【讨论】:

    • 我已经更新它以处理不区分大小写比较中的字母条件
    • 感谢您的回复。这种方法让我担心的一件事是性能,因为您基本上是在检索所有类别并对传递的字母进行循环。我将有很多类别,比如说 1000 个,特别是因为标签在 get_categories 中算作类别,所以希望有一种不同的方法。无论如何,我可以制作一个单独的 mysql 表,只存储每个字母的类别或其他东西......
    【解决方案2】:

    您可以使用临时 API 来缓存您的 sql 查询。

    【讨论】:

    • 我不关注,我为什么要添加过期时间的功能。我希望按字母字母生成类别表(不是标签)。你点击A,看到所有显示的以A开头的类别。transient api是如何连接的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2011-06-22
    相关资源
    最近更新 更多