wp query - How can you get first post, last post and post count in a category?

I want to show information about some categories on my site, which would include among other things:A link to the first

I want to show information about some categories on my site, which would include among other things:

  • A link to the first post in the category
  • A link to the last post in the category
  • The number of posts in the category

My plan so far was to use this in a WP_Query

$args= array(
      'cat'=>$comic,
      'orderby'=>'post_date',
      'order'=>'DESC',
      'post_type'=>'post',
      'posts_per_page'=>'-1');

And from there extract the information. But I'm not sure how to get to the first and last result without going through the whole loop, how to get the result count, or if using a WP_Query for this will slow the site down if the category grows too big.

I want to show information about some categories on my site, which would include among other things:

  • A link to the first post in the category
  • A link to the last post in the category
  • The number of posts in the category

My plan so far was to use this in a WP_Query

$args= array(
      'cat'=>$comic,
      'orderby'=>'post_date',
      'order'=>'DESC',
      'post_type'=>'post',
      'posts_per_page'=>'-1');

And from there extract the information. But I'm not sure how to get to the first and last result without going through the whole loop, how to get the result count, or if using a WP_Query for this will slow the site down if the category grows too big.

Share Improve this question asked Apr 11, 2020 at 23:05 metichimetichi 1375 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

You could use two separate query to get first & last post based on date.

$args = array(
    'cat' => $comic,
    'orderby' => 'post_date',
    'post_type' => 'post',
    'posts_per_page' => '1'
);

$first_post = $last_post = null;

// get first post
$first_post_query = new WP_Query( $args + array( 'order' => 'DESC' ) );
if ( $first_posts = $first_post_query->get_posts() ) {
    $first_post = array_shift( $first_posts );
}

// last post
$last_post_query = new WP_Query( $args + array( 'order' => 'ASC' ) );
if ( $last_posts = $last_post_query->get_posts() ) {
    $last_post = array_shift( $last_posts );
}

// post count: method 1
$post_count = $last_post_query->found_posts;


// post count: method 2
$category = get_category( $comic );
$post_count = $category->count;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744575862a4581735.html

相关推荐

  • wp query - How can you get first post, last post and post count in a category?

    I want to show information about some categories on my site, which would include among other things:A link to the first

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信