如何在Wordpress中获取帖子名称下的所有帖子类别?

时间:2014-01-07 13:43:02

标签: php mysql wordpress

我试图将Wordpress的所有类别都放在一行下,但问题在于它重复自身而不是在一行中输出。我的代码是

$query = mysql_query("SELECT p.post_title, p.post_content , t.slug, t.name, AVG(l.rating_rating) as average, l.rating_posttitle FROM wp_posts p
    INNER JOIN wp_ratings l ON l.rating_postid = p. ID
    INNER JOIN wp_term_relationships r ON r.object_id = p.ID
    INNER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id
    INNER JOIN wp_terms t ON t.term_id = x.term_id
    WHERE post_type ='post' 
    AND x.taxonomy = 'category'
    GROUP BY t.slug,p.post_title
    ") or die(mysql_error);

while($row = mysql_fetch_assoc($query)){


            $title = $row['rating_posttitle'];
            $rating = $row['average'];
            //$category = $row['slug'];
            $content = $row['post_content'];

            $query2 = mysql_query("SELECT t.slug FROM wp_terms t
            INNER JOIN wp_term_taxonomy x ON x.term_id = t.term_id
            INNER JOIN wp_term_relationships r ON r.term_taxonomy_id = x.term_taxonomy_id
            INNER JOIN wp_posts p ON p.ID = r.object_id
            INNER JOIN wp_ratings l ON l.rating_postid = p.ID 
            WHERE `rating_posttitle` = '$title'");

            while($row2 = mysql_fetch_assoc($query2)){
            $category = $row2['slug'];

            echo "<br>";
            echo $title . "<br>";
            echo $rating . "<br>";
            echo $category . "<br>";
            echo "<br>";    
            }

我得到的是:

Houston
4.0000
south


Houston
4.0000
central


Houston
4.0000
alternative

和我想要的是,

Houston
4.0000
alternative, central, south

任何帮助将不胜感激,

谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

while($row = mysql_fetch_assoc($query)){


      $title = $row['rating_posttitle'];
      $rating = $row['average'];
      $content = $row['post_content'];

      $query2 = mysql_query("SELECT t.slug FROM wp_terms t
      INNER JOIN wp_term_taxonomy x ON x.term_id = t.term_id
      INNER JOIN wp_term_relationships r ON r.term_taxonomy_id = x.term_taxonomy_id
      INNER JOIN wp_posts p ON p.ID = r.object_id
      INNER JOIN wp_ratings l ON l.rating_postid = p.ID 
      WHERE `rating_posttitle` = '$title'");

      echo "<br>";
      echo $title . "<br>";
      echo $rating . "<br>";
      $first = True;
      while($row2 = mysql_fetch_assoc($query2)){
            $category = $row2['slug'];    
            if(!$first)
                  echo ", " ;
            echo $category ;
            $first = False;

      }
      echo "<br>";    
}