WordPress的 - 添加“下一步”和“以前”链接到自定义博客页面
问题描述:
我正在寻找添加一个“下一步”和“以前”链接到我在Wordpress中建立的自定义博客页面。我设置了一个来自Bootstrap的自定义网格,但我想限制此网格每页12个帖子(出于明显的优化原因)。我是一名前端开发人员,所以对我来说计算PHP后端有点棘手。WordPress的 - 添加“下一步”和“以前”链接到自定义博客页面
如何在我的博客页面添加查询以包含下一个和上一个链接?我尝试了很多不同的解决方案,但似乎无法让它与我的循环一起工作。
谢谢!下面
代码:
<?php
/*
\t Template Name: Blog Page
*/
?>
<?php get_header(); ?>
<header class="entry-header">
<h1 class="entry-title"><?php echo get_the_title(); ?></h1>
</header>
<div class="container">
<?php
$args=array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 12
);
$my_query = null;
$my_query = new WP_Query($args);
if($my_query->have_posts()) {
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
if($i % 3 == 0) { ?>
<div class="row">
<?php
}
?>
<div class="col-md-4">
\t <h4><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h4>
\t \t <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(200,150)); ?></a>
\t \t <?php the_excerpt(); ?>
</div>
<?php $i++;
if($i != 0 && $i % 3 == 0) { ?>
</div><!--/.row-->
<div class="clearfix"></div>
<?php
} ?>
<?php
endwhile;
}
wp_reset_query();
?>
</div><!--/.container-->
<?php get_footer(); ?>
答
使用paginate_links
挂钩与自定义WP_Query
数组组合。确保为查询指定paged
数组参数。这会设置查询来返回分页结果。
<?php
// 1- Setup paging parameter
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// 2- Setup WP_query variable to get last 12 posts
$args = array(
'posts_per_page' => 12,
'orderby' => 'most_recent',
'paged' => $paged,
);
$the_query = new WP_Query($args);
// 3- Setup new loop
if($the_query->have_posts()) :
while($the_query->have_posts()) :
$the_query->the_post();
// 4- Output parameters you want here
echo '<div class="col-md-4">';
echo '<h4><a href="' . the_permalink() . 'title="Read more">' . the_title() . '</a></h4>';
echo '<a href="' . the_permalink() . '">' . the_post_thumbnail(array(200,150)) . '</a>';
echo the_excerpt();
echo '</div>';
// 5- close up loop
endwhile;
endif;
// 6- Output paginate_links just below post loop
echo paginate_links(array(
'base' => str_replace(999999, '%#%', esc_url(get_pagenum_link(999999))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $the_query->max_num_pages
));
// 7- reset post data query
wp_reset_postdata();
?>
答
这是一个相当普遍的问题 - 你可以在这里找到所有的信息https://codex.wordpress.org/Function_Reference/paginate_links
有一些例子,你也可以使用权一种方式
谢谢,我试过,但似乎无法得到它的工作。正如主题中提到的,我是前端开发人员而不是后端,所以我对使用PHP不太有信心。我如何将它添加到我现有的代码中,以便它可以工作? Thansk – viper2002
这将发生在您的其中一个模板文件中,并会在步骤#5中输出分页链接。步骤4是您要输出每个WP参数的位置。我更新了代码以更好地匹配你所做的,也许这更好? – staypuftman
感谢您的帮助。我使用了现有的代码,但必须修改几个部分才能使用我的主题。所有工作现在! – viper2002