GET_POST未按预期工作

时间:2012-01-01 作者:Steven

我正在尝试从3个不同类别中获取帖子,并将其列在首页上:

  // Carousel articles
  $args = array( \'numberposts\' => 3, \'orderby\' => \'date\', \'category\' => \'karusell\' );
  $carousel = get_posts($args);

  // News articles
  $args = array( \'numberposts\' => 3, \'orderby\' => \'date\', \'category\' => \'nyheter\' );
  $news = get_posts($args);

  // Featured articles - max 2 posts
  $args = array( \'numberposts\' => 2, \'orderby\' => \'date\', \'category\' => \'feature\' );
  $featured_posts = get_posts($args);
然后我通过以下操作输出它们:

foreach( $carousel as $post ) : setup_postdata($post);
 // code here
endforeach;
我的问题是,我的所有循环都输出相同的帖子。我是否使用了错误的函数来获取帖子?

我可以用这样的东西:

query_posts("category_name=feature&posts_per_page=2&orderby=date");
while (have_posts()) : the_post();
//code
endwhile;
但我希望我能把所有的文章放在代码的顶端,而不是“内联”。

2 个回复
最合适的回答,由SO网友:Velvet Blues 整理而成

具有get_posts(), 尝试使用类别ID而不是类别slug。

例如:

// Carousel articles
$args = array( \'numberposts\' => 3, \'orderby\' => \'date\', \'category\' => 1 );
$carousel = get_posts($args);

// News articles  
$args = array( \'numberposts\' => 3, \'orderby\' => \'date\', \'category\' => 2 );
$news = get_posts($args);

// Featured articles - max 2 posts
$args = array( \'numberposts\' => 2, \'orderby\' => \'date\', \'category\' => 3 );
$featured_posts = get_posts($args);

SO网友:daslicht

以下是另一种可能的解决方案:

$args = array(
    \'post_type\' => \'post\',        
    \'tax_query\' => array(
    array(
        \'taxonomy\' => \'category\',
        \'field\' => \'slug\',
        \'terms\' => \'karusell\'
    )
));
$posts = get_posts( $args );

结束

相关推荐