将分页添加到页面中的自定义帖子循环 [英] Adding pagination to custom post loop in page
问题描述
我创建了一个自定义页面模板(testimonials-page.php),在该模板中,我是 使用以下循环加载自定义帖子类型的推荐":
I have created a custom page template (testimonials-page.php) and in that template I am loading custom post type 'testimonials' using the following loop:
<?php query_posts(array(
'posts_per_page' => 5,
'post_type' => 'testimonials',
'orderby' => 'post_date',
'paged' => $paged
)
); ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="quote">
<?php echo get_the_post_thumbnail($id, array($image_width,$image_height)); ?>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
如何在其中添加分页?我安装了WP Paging插件,并且该插件正常工作 当我使用以下命令将分页调用到category.php时,效果很好:
How do I add pagination to that? I installed the WP Paging plugin, and while that plugin works great when I call the pagination into category.php using:
<p><?php wp_paging(); ?></p>
将相同的内容插入testimonial-page.php会导致格式损坏,并且链接 404在我身上.
Inserting the same thing into testimonial-page.php results in broken formatting and links that 404 on me.
推荐答案
首先,除非您打算修改默认的Wordpress Loop,否则切勿使用query_posts.
Firstly, never EVER use query_posts unless your intention is to modify the default Wordpress Loop.
相反,请切换到 WP查询.
这是我为使用所有内置Wordpress函数为客户端编写的主题编写的内容.到目前为止,它对我来说一直很好,所以我将尽我所能将其集成到您的代码中:
Here's something I wrote for a theme I did for a client using all built-in Wordpress functions. It's been working pretty well for me so far, so I'll integrate it into your code as best as I can:
global $paged;
$curpage = $paged ? $paged : 1;
$args = array(
'post_type' => 'testimonials',
'orderby' => 'post_date',
'posts_per_page' => 5,
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
?>
<div id="post-<?php the_ID(); ?>" class="quote">
<?php
echo get_the_post_thumbnail($post->ID, array($image_width,$image_height));
the_content();
?>
</div>
<?php
endwhile;
echo '
<div id="wp_pagination">
<a class="first page button" href="'.get_pagenum_link(1).'">«</a>
<a class="previous page button" href="'.get_pagenum_link(($curpage-1 > 0 ? $curpage-1 : 1)).'">‹</a>';
for($i=1;$i<=$query->max_num_pages;$i++)
echo '<a class="'.($i == $curpage ? 'active ' : '').'page button" href="'.get_pagenum_link($i).'">'.$i.'</a>';
echo '
<a class="next page button" href="'.get_pagenum_link(($curpage+1 <= $query->max_num_pages ? $curpage+1 : $query->max_num_pages)).'">›</a>
<a class="last page button" href="'.get_pagenum_link($query->max_num_pages).'">»</a>
</div>
';
wp_reset_postdata();
endif;
?>
2018年1月
还考虑使用 paginate_links ,因为它也是Wordpress内置的,并且具有更强大的选项和功能.
Jan 2018
Also consider using paginate_links, since it's also built into Wordpress, and has more robust options and capabilities.
这篇关于将分页添加到页面中的自定义帖子循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!