【问题标题】:WP Query to get posts with specific term_taxonomyWP Query 以获取具有特定 term_taxonomy 的帖子
【发布时间】:2014-06-27 13:36:27
【问题描述】:

在我的 wordpress 安装中,我有一个自定义分类法 event-categories,它映射到自定义帖子类型 event

在我的单个帖子显示页面中,我需要列出在当前帖子的同一 event-categories 中发布的所有帖子。我该如何为此编写 wp 查询?

自定义帖子中我的自定义分类的屏幕截图。

现在尝试像这样get_the_terms(the_ID(), 'event-categories')

所以我得到了与单个帖子相关的所有term_taxonomy_ids。接下来我怎样才能得到所有有这些term_taxonomy_id的帖子。

【问题讨论】:

  • 你试过了吗?
  • 当您说list all posts which is posted in same event-categories of the current post 时,您是指与当前帖子具有所有相同类别的所有帖子还是与当前帖子具有任何相同类别的所有帖子?我会根据你的回复更新我的答案
  • @celeriko 第二个选项,所有与当前帖子具有任何相同类别的帖子。

标签: php mysql wordpress wordpress-theming


【解决方案1】:

这将是解决您的问题的最基本查询。

$term_tax_ids = get_the_terms(get_the_ID(), 'event-categories');
$terms = array();

foreach($term_tax_ids as $term_tax_id) {
  array_push($terms, $term_tax_id->term_id);
}

$args = array(
  'post_type' => 'event',
  'posts_per_page' => 5,
  'tax_query' => array(
    array(
      'taxonomy' => 'event-categories',
      'field' => 'id',
      'terms' => $terms,
      'operator' => 'IN',
    )
  )
);

$query = new WP_Query( $args );

while ( $query->have_posts() ) {
  $query->the_post();
  echo '<div class="related_single">' . get_the_post_thumbnail();
  echo '<div class="related_title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></div></div>';
}

您真的应该阅读Codex,它几乎包含您想知道的有关查询的所有信息

【讨论】:

  • 第一行在屏幕上打印77,其余代码显示此错误Catchable fatal error: Object of class stdClass could not be converted to string in /var/www/html/wordpress/wp-includes/taxonomy.php on line 815
  • 啊抱歉那是因为get_the_terms 返回一个对象数组,我假设一个字符串数组,更新了我的答案
  • 我认为它工作正常,但有点困惑。您能帮我以这种 html 格式呈现这些带有 limit=5 的帖子吗?&lt;div class="related_single"&gt; &lt;!-- post image here --&gt; &lt;div class="related_title"&gt; &lt;!-- post title with post link --&gt; &lt;/div&gt; &lt;/div&gt;
  • 更新了我的代码以演示查询的简单显示,还请注意查询的 posts_per_page 参数。
  • 它没有进入最后一个while循环。注意:我还有一篇已检查所有类别的帖子。
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2019-05-18
  • 2022-06-29
  • 2017-11-23
  • 2012-08-08
  • 2015-11-30
  • 1970-01-01
相关资源
最近更新 更多