首先,确保模板文件命名为home.php
.
其次,在此上下文中不需要使用自定义查询循环。如果您只想在博客帖子索引(即“主页”)上显示3篇帖子,请通过以下方式过滤主循环查询pre_get_posts
:
function wpse83660_filter_pre_get_posts( $query ) {
if ( is_home() && $query->is_main_query() ) {
$query->set( \'posts_per_page\', \'3\' );
}
}
add_action( \'pre_get_posts\', \'wpse83660_filter_pre_get_posts\' );
您可以替换整个
recentPosts()
具有正常循环的函数。
瑟德,你打电话来the_content()
既在循环实例化之外,又希望它返回除返回内容以外的内容:
<?php get_header(); ?>
<?php the_content(); ?>
<?php get_footer(); ?>
此呼叫
get_content()
有2个问题:
尚未实例化循环:
if ( have_posts() ) : while ( have_posts() ) : the_post();
在博客帖子索引上下文中,此调用
the_content()
将返回博客帖子索引中帖子的内容,
not 指定为的*页的内容
page_for_posts
通过解决第二个问题,我们也可以解决第一个问题。
获取指定为的页面的post\\u内容page_for_posts
, 使用get_page()
, 然后通过它get_option( \'page_for_posts\' )
:
$page_object = get_page( get_option( \'page_for_posts\' ) );
然后,输出其结果:
if ( ! is_null( $page_object ) ) {
echo apply_filters( \'the_content\', $page_object->post_content );
}
因此,整个模板文件如下所示:
/**
* Blog posts index template file
*
* Displays the blog posts index
*
* @filename: home.php
*/
get_header();
if ( have_posts() ) : while ( have_posts() ) : the_post();
<a href="<?php the_permalink();?>"><?php the_post_thumbnail(\'recent-thumbnails\'); ?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h2>
<?php the_content(); ?>
endwhile; endif;
$page_object = get_page( get_option( \'page_for_posts\' ) );
if ( ! is_null( $page_object ) ) {
echo apply_filters( \'the_content\', $page_object->post_content );
}
get_footer();