php 如何在WordPress中让分页为get_posts()工作?

lzfw57am  于 2023-04-10  发布在  PHP
关注(0)|答案(6)|浏览(114)

我在一个WordPress网站上工作,我已经创建了一个页面模板,通过类别slug显示帖子。为此,我为页面创建了一个字段WP_Catid,并将其设置为我想要显示帖子的类别slug。然而,我只希望每页显示五个帖子,并在这些帖子的底部显示分页链接。如何正确显示分页链接?
代码如下:

<div id="container">
  <div id="content" role="main">
    <?php
      $btpgid=get_queried_object_id();
      $btmetanm=get_post_meta( $btpgid, 'WP_Catid','true' );
      $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

      $args = array( 'posts_per_page' => 5,
                     'category_name' => $btmetanm,
                     'paged' => $paged,
                     'post_type' => 'post' );

      $myposts = get_posts( $args );
      foreach ( $myposts as $post ) : setup_postdata( $post ); 
        echo "<div style='border:2px groove black; margin-bottom:5px;'><h3 class='btposth'>";
        the_title(); 
        echo "</h3><div class='btpostdiv'>";
        the_content();
        echo "</div></div>";
      endforeach; 
      next_posts_link( 'Older Entries'); //not displaying
      previous_posts_link('Newer Entries &raquo;'); //not displaying
      wp_reset_postdata();
    ?>
  </div><!-- #content -->
</div><!-- #container -->
o2rvlv0m

o2rvlv0m1#

简单来说,如果你需要分页查询,不要使用get_posts。如果你要使用一个不需要分页的自定义查询,get_posts可以很好地工作,但是当你需要引入分页时,它真的会变得很复杂。
我认为这里最简单和最合适的方法是使用WP_Query来构造您的自定义查询,也就是说,如果您不能使用pre_get_posts来改变主查询以从主查询中获得所需的输出。
我认为next_posts_link()previous_posts_link()更适合用于自定义查询,即WP_Query。但是,当您使用自定义查询时,您必须记住设置$max_pages参数,否则您的分页将中断
通过一些小的调整,您的查询应该如下所示

<div id="container">
<div id="content" role="main">
<?php
$btpgid=get_queried_object_id();
$btmetanm=get_post_meta( $btpgid, 'WP_Catid','true' );
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array( 'posts_per_page' => 5, 'category_name' => $btmetanm,
'paged' => $paged,'post_type' => 'post' );
    $postslist = new WP_Query( $args );

    if ( $postslist->have_posts() ) :
        while ( $postslist->have_posts() ) : $postslist->the_post(); 

             echo "<div style='border:2px groove black; margin-bottom:5px;'><h3 class='btposth'>";
                 the_title(); 
             echo "</h3><div class='btpostdiv'>";
                 the_content();
             echo "</div></div>";

         endwhile;  

             next_posts_link( 'Older Entries', $postslist->max_num_pages );
             previous_posts_link( 'Next Entries &raquo;' ); 
        wp_reset_postdata();
    endif;
    ?>

</div><!-- #content -->
</div><!-- #container -->
anhgbhbe

anhgbhbe2#

Pieter Goosen's answer是完全正确的,他建议使用WP_Query是最有意义的。然而,我在循环外寻找get_posts分页时偶然发现了这个问题,所以我想这对其他人来说也是一个有用的替代方案:
get_posts有一个直接属性offset,它实现了与WP_Query中的paged几乎相同的功能;但是其中paged指的是分页(例如 1,2,3),offset是你想要偏移查询的实际 * 文章数量 *(例如 5,10,15)。通过一点数学运算-numberToShow * pageNumber-你可以很容易地得到正确的偏移量:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 0;

$postsPerPage = 5;
$postOffset = $paged * $postsPerPage;

$args = array(
    'posts_per_page'  => $postsPerPage,
    'category_name'   => $btmetanm,
    'offset'          => $postOffset,
    'post_type'       => 'post'
);

$myposts = get_posts($args);

本例中的初始paged值是0而不是1,因为当乘以posts_per_page时,您希望初始偏移量是0而不是5
如果您想要更细粒度的控制而不是简单的分页,这可能是最方便的,但与接受的答案中的循环结合使用也应该同样有效。

yhqotfr8

yhqotfr83#

尝试更改$args:

$args = array( 
'posts_per_page' => 5,
'category_name' => $btmetanm,
'post_type' => 'post',
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 )
   );

在loop之后,我们会这样写:

if (function_exists('wp_pagenavi')) {
wp_pagenavi();
}
gojuced7

gojuced74#

我不会告诉你使用get_posts()是正确的做法...但这里是我使用get_posts()设置的一些基本分页代码。
编辑:正如Pieter指出的那样,这并不意味着要在生产代码中使用。但无论如何,我只是在尝试使用get_posts()来查看是否可以使用分页。如果您在生产环境中,您不会想要使用它。

$cpt_name = 'post-type'; //add your own post type

//what pagination page are we on?
if(! empty($_GET['pag']) && is_numeric($_GET['pag']) ){
    $paged = $_GET['pag'];
}else{
    $paged = 1;
}
//you could use this if you want, just make sure to use "/page/2" instead of "?pag=2" in the pagination links.
//$paged = (get_query_var('paged')) ? get_query_var('paged') : 0;

//how many posts should we display?
$posts_per_page = (get_option('posts_per_page')) ? get_option('posts_per_page') : 10; 

//let's first get ALL of the possible posts
$args = array(
        'posts_per_page'   => -1,
        'orderby'          => 'title',
        'order'            => 'ASC',
        'fields'           => 'ids',
        'post_type'        => $cpt_name
    );

$all_posts = get_posts($args);

//how many total posts are there?
$post_count = count($all_posts);

//how many pages do we need to display all those posts?
$num_pages = ceil($post_count / $posts_per_page);

//let's make sure we don't have a page number that is higher than we have posts for
if($paged > $num_pages || $paged < 1){
    $paged = $num_pages;
}

//now we get the posts we want to display
$args = array(
        'posts_per_page'   => $posts_per_page,
        'orderby'          => 'title',
        'order'            => 'ASC',
        'post_type'        => $cpt_name,
        'paged'        => $paged
    );

$my_posts = get_posts($args);

//did we find any?
if(! empty($my_posts)){

    echo '<div id="my-posts-wrapper">';

    //THE FAKE LOOP
    foreach($my_posts as $key => $my_post){
                //do stuff with your posts
        echo '<div class="my-post">'.$my_post->post_title.'</div>';

    }

    echo '</div>';

    //we need to display some pagination if there are more total posts than the posts displayed per page
    if($post_count > $posts_per_page ){

        echo '<div class="pagination">
                <ul>';

        if($paged > 1){
            echo '<li><a class="first" href="?pag=1">&laquo;</a></li>';
        }else{
            echo '<li><span class="first">&laquo;</span></li>';
        }

        for($p = 1; $p <= $num_pages; $p++){
            if ($paged == $p) {
                echo '<li><span class="current">'.$p.'</span></li>';
            }else{
                echo '<li><a href="?pag='.$p.'">'.$p.'</a></li>';
            }
        }

        if($paged < $num_pages){
            echo '<li><a class="last" href="?pag='.$num_pages.'">&raquo;</a></li>';
        }else{
            echo '<li><span class="last">&raquo;</span></li>';
        }

        echo '</ul></div>';
    }
}

我希望有人能从中得到一些好处:)
编辑:管他呢!用错误的方式做一些事情...还不如把它做对!这里也有一些更少的(没有任何mixin)。

.pagination             { margin: 30px 0px;
    ul                    { display:block; list-style-type:none; margin:0 auto; padding: 0px; 
      li                  { display:inline-block; list-style-type:none; margin:0; padding:0;
        a, span           { display:inline-block; font-size: 14px; width:auto; min-width:26px; height:26px; line-height: 26px; border: 1px solid #dddddd; border-right: 0px; background:#FFFFFF; color:#FF0000; padding: 5px; text-align: center;
          &:hover         { cursor:pointer; text-decoration:none; }

          &.first         { border-top-left-radius: 3px; border-bottom-left-radius: 3px; }
          &.last          { border-top-right-radius: 3px; border-bottom-right-radius: 3px;}
        }

        span.last,
        span.first        { color: #FF0000;
            &:hover       { cursor: default; }
        }

        a.last,
        a.first           { 
            &:hover       {  }
        }

        a:hover, 
        &.active a, 
        .current          { background:#FF0000; color:#ffffff; border-color: #b21712; }

        &:last-child      { 
            a, span       { border-right: 1px solid #dddddd; }

            a             { 
                &:hover   { border-color: #FF0000; }
            }
        }
      }
    }
}
pbossiut

pbossiut5#

WordPress文章分页码(新增)

复制并粘贴这段代码,并享受它。:)

<?php
 
$currentPage = get_query_var('paged');
 
 
// General arguments
 
$posts = new WP_Query(array(
    'post_type' => 'post', // Default or custom post type
    'posts_per_page' => 10, // Max number of posts per page
    //'category_name' => 'My category', // Your category (optional)
    'paged' => $currentPage
));
 
 
// Top pagination (pagination arguments)
 
echo "<div class='page-nav-container'>" . paginate_links(array(
    'total' => $posts->max_num_pages,
    'prev_text' => __('<'),
    'next_text' => __('>')
)) . "</div>";
 
 
// Content display
 
if ($posts->have_posts()) :
    while ($posts->have_posts()) :
        $posts->the_post();
        echo "<div class='post-wrap'>";
        the_title();
        the_content();
        echo "</div>";
    endwhile;
endif;
 
 
// Bottom pagination (pagination arguments)
 
echo "<div class='page-nav-container'>" . paginate_links(array(
    'total' => $posts->max_num_pages,
    'prev_text' => __('<'),
    'next_text' => __('>')
)) . "</div>";
 
?>
s4n0splo

s4n0splo6#

//pagination to work for get_posts() in WordPress.    
//Step-1.    
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;    
 $args = array( 'posts_per_page' => 4,         
               'order'    => 'DESC',    
               'orderby' => 'ID',    
               'paged' => $paged                                   
                    );   
                    $query = get_posts($args);  
                    foreach ($query as $key => $value) {  
                      echo get_the_title($value->ID);  
                     }  
step-2    
//Get total post count    
   $args = array( 'posts_per_page' => -1, 
                  'order'    => 'DESC',
                  'orderby' => 'ID'
                  );    
$totalPost = get_posts($args);    
$numberOftotalpost = count($totalPost);    
$maxNumberOfPage =  ceil($numberOftotalpost/4);   
    
//call pagination function    
   
echo pagination_bar($maxNumberOfPage);

//分页函数

function pagination_bar( $maxNumberOfPage ) {

    $total_pages = $maxNumberOfPage;
    $big = 999999999; // need an unlikely integer

    if ($total_pages > 1){
        $current_page = max(1, get_query_var('paged'));

        echo paginate_links(array(
            'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format' => '?paged=%#%',
            'current' => $current_page,
            'total' => $total_pages,
                        'prev_text' => __('« Previous'),
                        'next_text' => __('Next »'),
        ));
    }
}

相关问题