注意:我知道这不是最有效的方法,特别是如果您有成千上万的帖子。我有兴趣看到更好的方法来获得下一篇文章。
将以下内容添加到您的 functions.php 文件中:
/*
* Session Tracking
*/
add_action('init', 'start_session', 1);
function start_session() {
if(!session_id()) {
session_start();
}
}
// Update Cookie trail
function update_cookie_trail() {
$_SESSION['ref_category'] = get_query_var('cat');
}
/*
* Return next post based off of cookies
*/
function next_post_from_session($text, $categories) {
global $post;
$cat_array = explode(',', $categories);
$cat_array[] = $_SESSION['ref_category'];
// Get all posts, exclude Hidden cat
$args = array(
'numberposts' => -1,
'category' => implode(',', $cat_array),
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$allPosts = get_posts( $args );
$index = 0;
foreach( $allPosts as $thePost ) {
$index++;
if($post->ID == $thePost->ID) {
$nextPost = $allPosts[$index++];
$url = get_permalink($nextPost->ID);
$a = '<a href="'.$url.'" title="'.esc_attr($nextPost->post_title).'" />'.$text.'</a>';
return $a;
}
}
}
/*
* Return previous post based off of cookies
*/
function previous_post_from_session($text, $categories) {
global $post;
$cat_array = explode(',', $categories);
$cat_array[] = $_SESSION['ref_category'];
// Get all posts, exclude Hidden cat
$args = array(
'numberposts' => -1,
'category' => implode(',', $cat_array),
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$allPosts = get_posts( $args );
$index = 0;
foreach( $allPosts as $thePost ) {
if($post->ID == $thePost->ID) {
$prevPost = $allPosts[$index-1];
$url = get_permalink($prevPost->ID);
$a = '<a href="'.$url.'" title="'.esc_attr($prevPost->post_title).'" />'.$text.'</a>';
return $a;
}
$index++;
}
}
/*
* Generate a "back" URL to the previous category page based off session data
*/
function previous_category_permalink() {
$ref_url = $_SESSION['ref_category'];
return get_category_link($ref_url);
}
然后在显示多个博客文章的任何 category.php 或页面(如“相关文章”部分)上,运行此函数:
update_cookie_trail();
然后在您的 single.php 上,您可以使用以下功能。
<?php echo next_post_from_session('Next', '-24, 10'); ?>
<a class="close" href="<?php echo previous_category_permalink(); ?>">
Back
</a>
<?php echo previous_post_from_session('Previous Post', '-24, 10'); ?>
'-24, 10' 是一个参数,允许您通过逗号分隔的 ID 排除或特别包含类别。