谁能帮我在这个查询中添加类别id,这样就可以返回某个类别的帖子了吗?

时间:2018-07-24 作者:Mahmud Farooque

有人能帮我在这个查询中添加类别id,这样就可以返回某个类别的帖子吗?提前谢谢。

<?php foreach(_get($wp_query->posts? : array()) as $n => $post){ setup_postdata($post); ?>

    // HTML and post Tags

<?php } ?>

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

请遵循正确的wordpress方法,不要遵循任何人的代码或复制粘贴代码。

 /*
 * CODEX: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters
 * Source: https://core.trac.wordpress.org/browser/tags/3.9/src/wp- 
 includes/query.php
 */
$args = array(

//////Category Parameters - Show posts associated with certain categories.
//http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
 //all categories parameter 

\'cat\' => 5,//(int) - use category id.
\'category_name\' => \'staff, news\',          //(string) - Display posts that 
  have these categories, using category slug.
\'category_name\' => \'staff+news\',           //(string) - Display posts that 
 have "all" of these categories, using category slug.
\'category__and\' => array( 2, 6 ),         //(array) - use category id.
\'category__in\' => array( 2, 6 ),          //(array) - use category id.
\'category__not_in\' => array( 2, 6 ),      //(array) - use category id.
\'post_type\' => \'post\', //post or you can use your custom post type 
\'post_status\' => \'publish\',
\'order\' => \'DESC\',
\'orderby\' => \'date\');

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
   $the_query->the_post();
    // Do Stuff
  } // end while
} // endif
// Reset Post Data
wp_reset_postdata();

SO网友:Mahmud Farooque

就这样解决了。谢谢大家。

<?php
$q = new WP_Query(array(
    \'post_type\' => \'post\',
    \'posts_per_page\' => \'1\',
    \'fields\' => \'ids\',
    \'cat\' => \'8\'
));
foreach(_get($q->posts? : array()) as $post){
    setup_postdata($post);?>

          // HTML and post Tags

<?php } ?>

结束