首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress: get-post是空的

Wordpress: get-post是空的
EN

Stack Overflow用户
提问于 2015-12-21 16:42:53
回答 2查看 2.5K关注 0票数 0

我在Wordpress中创建了一个定制的post类型,并为它创建了一个分类。现在,我想显示分类法-术语,在每个术语下显示具有该术语的帖子。我正试着用get_posts来实现这一点,但是get-posts却是空的。下面是我的代码,上面有关于所发生的事情的注释:

代码语言:javascript
复制
<?php
//for each category, show all posts
$cat_args=array(
  'orderby' => 'name',
  'order' => 'ASC',
  'taxonomy' => 'teachres-categorie',
  'post_type'=> 'biology'
);

$categories=get_categories($cat_args);

foreach($categories as $category) {
$args=array(
   'showposts' => -1,
   'category' => array($category->term_taxonomy_id),
   'ignore_sticky_posts'=>1,
   'post_type'=> 'biology', 
   'taxonomy' => 'teachres-categorie'
 );
 ?> 

 <h2><?php  echo '<p>Category: <a href="' . get_category_link($category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';?></h2>
 <p><?php echo $category->term_taxonomy_id; ?></p> 

 //this gets displayed just fine, meaning $category-array is filled

 <?php
 $posts = get_posts($args);

 //at this point $args is filled: Array ( [showposts] => -1 [category] => Array ( [0] => 34 ) [ignore_sticky_posts] => 1 [post_type] => biology [taxonomy] => teachres-categorie ) 
 //at this point $posts is empty: Array ( ) 

   if ($posts) {

    //This never gets executed as $posts is empty

     foreach($posts as $post) {
    // ...so we'll never get to here            

     } // end foreach($posts
   } // end if ($posts
 } // // end foreach($categories
?>

除了这段代码之外,我没有修改主查询,这些是页面上唯一的循环。当我搜索这个问题时,有更多的人有同样的问题,但是他们的解决方案对我没有帮助。

有人能告诉我为什么get_posts是空的吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-21 18:41:32

我将使用tax_query,而不是您在post中按类别获取帖子的方式。此外,posts_per_page取代了展示,但它可能没有那么关键。试试这个:

代码语言:javascript
复制
$args = array(
   'posts_per_page' => -1,
   'ignore_sticky_posts' => 1,
   'post_type'=> 'biology', 
   'tax_query' => array(
       array(
       'taxonomy' => 'teachres-categorie',
       'field' => 'term_id',
       'terms' => $category->term_id,
       ),
    )
);

$posts = get_posts($args);

这些args将查询所有具有term_id (它是循环中类别的id )的帖子,检索该类别项中的所有帖子。

此外,@vard对类别参数提出了一个很好的观点,我认为它回答了您关于为什么它可能不起作用的问题。

票数 0
EN

Stack Overflow用户

发布于 2015-12-21 17:38:48

get_posts参数中很少有错误。考虑到您实际上有以下基于您的评论:

代码语言:javascript
复制
$posts = get_posts(array(
   'showposts' => -1,
   'category' => array(0 => 34),
   'ignore_sticky_posts' => 1,
   'post_type'=> 'biology', 
   'taxonomy' => 'teachres-categorie'
));
  • category参数期望一个整数(类别的id)或包含逗号分隔的类别id列表的字符串。从医生那里: 类别参数可以是逗号分隔的类别列表,因为get_posts()函数将“类别”参数作为“cat”直接传递给WP_Query

然后,如果您查看WP_Query文档,您将看到类别的数组值仅用于category__andcategory__incategory__not_in参数。我认为这就是为什么您的查询一开始不检索任何帖子的原因。

  • taxonomy参数不存在。在发送分类法段塞之前有一个tax参数,但是从3.1版开始就不再推荐它了。如果您想根据分类法查询您的帖子,请使用tax_query参数。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34400469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档