【问题标题】:Wordpress Get Category From Post TableWordpress 从帖子表中获取类别
【发布时间】:2017-12-15 06:33:43
【问题描述】:

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

 <?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 );
  ?>

【问题讨论】:

  • csv 在哪里?

标签: php mysql wordpress categories


【解决方案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();

【讨论】:

  • 只需添加; setup_postdata($post) 之后
  • 有效!但是我如何才能从特定类别(如 2、3、4 等中的 cat_id)中获取逗号分隔值的帖子标题
  • 你可以使用 get_the_category_by_ID( int $cat_ID )
  • 然后从该类别获取帖子 10, 'category' => $category_id, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true ); $posts_array = get_posts($args); ?>
猜你喜欢
  • 1970-01-01
  • 2011-05-16
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2017-04-23
  • 1970-01-01
相关资源
最近更新 更多