Wordpress从帖子表获取类别

时间:2017-12-15 06:33:44

标签: php mysql wordpress categories

我试图用逗号分隔的值显示最后几个帖子标题和下面的代码。这是我从wp_post table进行查询。现在如何在此代码中获取该类别,因为没有category表中wp_post的列。下面是我的代码

 <?php
      $posts = $wpdb->get_col("
      SELECT $wpdb->posts.*
      FROM $wpdb->posts
      WHERE post_status = 'publish' 
      and post_type='post'

      ORDER BY post_date DESC LIMIT 10");

      $the_posts = array();
      foreach($posts as $post) :
      echo implode( ', ', $the_posts );
  ?>

1 个答案:

答案 0 :(得分:1)

你可以这样做:

1 - 获取帖子(wp的正确方法)

<?php 
     $args = array(
    'posts_per_page'   => 10,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'suppress_filters' => true 
);
$posts_array = get_posts( $args ); ?>

2 - 循环帖子并获取类别

foreach($posts_array as $post):setup_postdata($post);
     $category = get_the_category();
     var_dump($category);
endforeach;
wp_reset_postdata();