现有的WordPress功能仅用于显示上一篇或下一篇文章。我很快编写了显示任意数量帖子的函数。
在主题函数中粘贴以下内容。php文件:
function custom_get_adjacent_posts( $in_same_cat = false, $previous = true, $limit = 2 ) {
global $post, $wpdb;
$op = $previous ? \'<\' : \'>\';
if ( $in_same_cat ) {
$cat_array = wp_get_object_terms($post->ID, \'category\', array(\'fields\' => \'ids\'));
$join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = \'category\' AND tt.term_id IN (" . implode(\',\', $cat_array) . ")";
}
$posts = $wpdb->get_results( $wpdb->prepare( "SELECT p.* FROM wp_posts AS p $join WHERE p.post_date $op \'%s\' AND p.post_type = \'post\' AND p.post_status = \'publish\' ORDER BY p.post_date DESC LIMIT $limit", $post->post_date, $post->post_type ) );
return $posts;
}
function custom_adjacent_posts_links( $in_same_cat = false, $previous = true, $limit = 2 ) {
$prev_posts = custom_get_adjacent_posts( $in_same_cat, $previous, $limit );
if( !empty($prev_posts) ) {
echo ($previous) ? \'<h3>Previous Posts:</h3>\' : \'<h3>Next Posts:</h3>\';
echo \'<ul>\';
foreach( $prev_posts as $prev_post ) {
$title = apply_filters(\'the_title\', $prev_post->post_title, $prev_post->ID);
echo \'<li><a href="\' . get_permalink( $prev_post ) . \'">\' .$title . \'</a></li>\';
}
echo \'</ul>\';
}
}
在要显示帖子的侧栏文件中,使用
custom_adjacent_posts_links( true );
显示同一类别中的前两篇文章,以及
custom_adjacent_posts_links( true, false );
显示同一类别中的下两篇文章。