怎么使用transients缓存wp_query(带分页)?

先看下缓存wp_query(带分页)的需求:

I have seen examples where there is a fix number of posts to be queried; however, I cant find an example when using pagination.

I am trying to figure out how to use transients to cache a WP_Query with paging.

So far, I am showing 12 posts per page. When I load the next set of posts, the posts are the same first 12 posts. It is not getting the following posts.

要自定义wp_query分页的缓存,这样可以减少SQL查询,提高性能,需要用到 get_transientset_transient两个函数。

示例代码:

<?php

  $my_posts_query = get_transient( 'my_unique_transient_key_' . get_query_var( 'paged' ) );

  if( false === $my_posts_query ) {

    $args = array( 'post_type' => 'post', 'posts_per_page' => '12', 'paged' => $paged );
    $my_posts_query = new WP_Query( $args );

    set_transient( 'my_unique_transient_key_' . get_query_var( 'paged' ), $my_posts_query, 300 );
  }

  if ( $my_posts_query->have_posts() ) :

    while ( $my_posts_query->have_posts() ) :

      $my_posts_query->the_post();

      // Your loop

    endwhile;

    // This is responsible for 1, 2, 3 pagination links. You can easily change this to previous and nexys links.
    if ( $my_posts_query->max_num_pages > 1 ) :
      $big = 999999999;
      echo '<div class="pagination">';
      echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $my_posts_query->max_num_pages
      ) );
      echo '</div>';
    endif;

  endif;

  wp_reset_postdata();

?>

发表评论

您的电子邮箱地址不会被公开。