php 分页自定义查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 分页自定义查询相关的知识,希望对你有一定的参考价值。

// In order for pagination to work with a custom query, the global posts_per_page
// must be lower or equal than the 'posts_per_page' argument in your query
// this can be set in settings->reading for all post types
// I have chosen to override the setting for news here
// to ensure the pagination cannot be broken if the setting gets changed

add_action( 'pre_get_posts',  'set_posts_per_page'  );

function set_posts_per_page( $query ) {

  global $wp_the_query;
  
  // note: in this scenario the query is running in archive.php
  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) && is_post_type_archive( 'news' ) ){
    $query->set( 'posts_per_page', 1 );
  }

  return $query;
}
  <div class="list-posts">
    
    {% if news %}
      {% for item in news %}

        <article class="post-snippet">
          <p class="post-cat">{% if item.post_type == 'position-statement' %}Position Statement{% else %}News{% endif %}</p>
          <h1 class="post-title">
            <a href="{{item.link}}">
              {{item.title}}
            </a>
          </h1>
          <p class="post-excerpt">
            {{item.get_preview(33)}}
          </p>
          <p class="post-date">
            {{item.date}}
          </p>
        </article>
      {% endfor %}
    {% else %}
      <p>No news...</p>
    {% endif %}

    {% include 'partials/pagination.twig' %}

  </div>
global $paged;
if (!isset($paged) || !$paged){
    $paged = 1;
}
 
$context = Timber::get_context();
 
$args_news = array(
  'post_type' => 'news',
  'orderby' => 'date',
  'posts_per_page' => 2,
  'paged' => $paged,
);
$context['news'] = Timber::get_posts( $args_news );
$context['pagination'] = Timber::get_pagination();

以上是关于php 分页自定义查询的主要内容,如果未能解决你的问题,请参考以下文章

PHP wordpress分页自定义查询

没有模型 APIView 的 DRF 分页自定义响应

Laravel 5.2 分页自定义

swift 中心分页自定义布局

页面分页自定义插件

angularjs前端分页自定义指令pagination