在WordPress中,如果自定义文章类型(Custom Post Type)的文章无法在首页显示,可能是因为默认的主循环(have_posts() 和 the_post())只会查询默认的 post 类型文章,而不会自动包含自定义文章类型的文章。
要解决这个问题,你可以通过以下几种方式来确保自定义文章类型的文章在首页显示:
方法1:使用 pre_get_posts 钩子修改主查询
你可以在主题的 functions.php 文件中使用 pre_get_posts 钩子来修改主查询,使其包含自定义文章类型的文章。
function zzw_include_custom_post_types_in_homepage( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'your_custom_post_type' ) ); // 将 'your_custom_post_type' 替换为你的自定义文章类型名称
}
}
add_action( 'pre_get_posts', 'zzw_include_custom_post_types_in_homepage' );方法2:直接修改首页模板中的查询
你也可以直接在首页模板中修改查询,使用 WP_Query 来获取自定义文章类型的文章。
$args = array(
'post_type' => array( 'post', 'your_custom_post_type' ), // 将 'your_custom_post_type' 替换为你的自定义文章类型名称
'paged' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
get_template_part( 'listli-noimg/terms1-li' ); // 样式
endwhile;
// 分页
the_posts_pagination( array(
'prev_text' => __( '上一页', 'textdomain' ),
'next_text' => __( '下一页', 'textdomain' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'textdomain' ) . ' </span>',
) );
wp_reset_postdata(); // 重置查询
else :
_e( '暂时没有内容。', 'textdomain' );
endif;方法3:使用插件
如果你不想修改代码,可以使用一些插件来帮助你在首页显示自定义文章类型的文章。例如,插件 “Custom Post Type UI” 或 “Query Multiple Taxonomies” 可以帮助你实现这一功能。
注意事项
- 分页问题:如果你使用了自定义查询(如方法2),确保分页参数正确传递,否则分页可能无法正常工作。
- 性能考虑:如果你在首页加载了大量的文章(包括自定义文章类型),可能会影响页面加载速度。确保优化查询或使用分页来减少一次性加载的文章数量。
通过以上方法,你应该能够成功在首页显示自定义文章类型的文章。

