• wordpress CMS主题:ssmay主题wordpress CMS主题:ssmay主题
  • 首页 > wordpress CMS主题制作 > wordpress主题如何获取同一标签下的关联分类

    wordpress主题如何获取同一标签下的关联分类

    作者: 分类:wordpress CMS主题制作 点击: 2,100 次
    wordpress CMS主题:ssmay主题

      在开发wordpress主题的过程中,我们可能会有这样的需求,既然可以获取某个分类的关联标签,那么,我们能获取某个标签的关联分类吗?答案是肯定的。以下提供一个获取同一标签下的关联分类的函数:

      function ludou_get_tag_categories($args) {
      global $wpdb;
      $categories = $wpdb->get_results
      ("
      SELECT DISTINCT terms1.term_id as cat_id
      FROM
      $wpdb->posts as p1
      LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
      LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
      LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,
      $wpdb->posts as p2
      LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
      LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
      LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
      WHERE
      t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms2.term_id IN (".$args['tags'].") AND
      t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
      AND p1.ID = p2.ID
      ORDER by cat_id
      ");
      $count = 0;

      if($categories) {
      foreach ($categories as $category) {
      $mycategory[$count] = get_term_by('id', $category->cat_id, 'category');
      $count++;
      }
      }
      else {
      $mycategory = NULL;
      }

      return $mycategory;
      }

      下面是一个简单的函数调用范例:

      $args = array( 'tags' => '12,13');// 定义一个tag数据,存放多个tagID,12,13是标签ID,多个用英文逗号隔开
      $categories = ludou_get_tag_categories($args);// 调用上面定义的函数,来获取ID为12,13的标签的关联分类
      // 输出我们获取到的关联分类,以列表形式打印
      $content .= "<ul>";
      if(!empty($categories)) {
      foreach ($categories as $category) {
      $content .= "<li><a href=\"".get_category_link( $category->term_id )."\">".$category->name."</a></li>";
      }
      }
      $content .= "</ul>";
      echo $content;

      通过上面的代码,我们在wordpress主题中实现了调用同一标签下的关联分类,并列举了一个简单案例,当然,你还可以更加深入一点。

    文章作者:高时银博客
    本文地址:http://wanlimm.com/77201601064951.html
    本文时间:2016-01-06 10:57:26
    版权所有 © 转载时必须以链接形式注明作者和原始出处!

    上一篇:
    下一篇:
    wordpress CMS主题:ssmay主题

    或许你会感兴趣的文章:

    发表评论

    电子邮件地址不会被公开。 必填项已用*标注

    This site uses Akismet to reduce spam. Learn how your comment data is processed.