WP与PHP:如何在get_template_part()后拼接自定义函数?
问题根源
你当前的核心问题是把custom_function()放在了主循环内部(即while ( have_posts() ) : the_post();的分支逻辑里),导致每输出一篇主题帖子就触发一次补充帖子的输出,自然出现交替显示的情况。
解决方案
要实现「先输出所有主题帖子,再统一输出补充帖子」,需要将custom_function()的调用移到主循环完全结束之后,同时增加帖子数量的判断逻辑:
步骤1:修改主循环逻辑,统计实际输出的主题帖子数
在你的模板文件(如index.php、archive.php等)中,找到主循环代码,调整如下:
// 初始化计数器,统计实际输出的主题帖子数量 $main_post_count = 0; // 执行主循环 if ( have_posts() ) : while ( have_posts() ) : the_post(); // 保留你原有的帖子筛选逻辑 if ( 'post' === get_post_type() && ! in_category( $custom_cats, get_the_ID() ) ): get_template_part( 'template-parts/blog/' . $custom_layout . '/content' ); $main_post_count++; // 每输出一篇主题帖,计数器+1 endif; endwhile; // 循环结束后,判断是否需要补充帖子 // 获取全局的posts_per_page设置,若为自定义查询则用 $wp_query->get('posts_per_page') $required_posts = get_option( 'posts_per_page' ); if ( $main_post_count < $required_posts ) { // 调用自定义函数输出补充帖子 custom_function(); } else : // 无主题帖子时的默认处理 get_template_part( 'template-parts/content', 'none' ); endif;
步骤2:优化custom_function()避免循环冲突
确保自定义函数内的查询不会干扰主循环,结尾必须重置查询:
function custom_function() { // 计算需要补充的帖子数量(可选,按需调整) global $main_post_count; $required_posts = get_option( 'posts_per_page' ); $need_supplement = $required_posts - $main_post_count; $args = array( 'post_type' => 'post', 'posts_per_page' => $need_supplement, // 按需设置补充数量 'tax_query' => array( // 你的分类筛选逻辑 ) ); $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); // 复用主题帖子模板输出补充内容 get_template_part( 'template-parts/blog/' . $custom_layout . '/content' ); endwhile; wp_reset_postdata(); // 重置主循环,避免后续模板出错 endif; }
你之前方法无效的原因
- 方法1:
get_template_part()是直接输出内容的函数,返回值为null,用.拼接会触发类型错误,导致致命错误。 - 方法2/3/4:所有操作都在主循环内部执行,每循环一次主题帖就调用一次
custom_function(),必然出现交替输出。 locate_template():你之前的调用大概率是模板路径错误导致致命错误,且它本身仅用于加载模板文件,无法解决输出顺序问题。
内容的提问来源于stack exchange,提问作者xii
相关产品推荐
相关产品推荐

