WordPress Genesis主题相关文章脚本报错:have_posts()调用空对象
解决Genesis主题下相关文章脚本在页面(Pages)触发的致命错误
问题根源
你碰到的这个致命错误本质是变量未初始化:WordPress的页面(Pages)默认没有关联分类,所以get_the_category()在页面会返回空数组,导致你的脚本里$the_related_posts = new WP_Query($args);这行代码根本没执行。当后续代码尝试调用$the_related_posts->have_posts()时,这个变量还是null,自然就抛出了“Call to a member function on null”的错误。
另外你的代码还有两个小问题:函数里直接用$post->ID可能存在作用域问题,同时代码结构里有多余的闭合大括号,导致逻辑混乱。
完整解决方案
下面是修正后的代码,我标注了关键修改点:
add_action( 'genesis_after_entry_content', 'mt_related_posts', 12 ); function mt_related_posts() { // 1. 只在单篇文章页面运行脚本,直接避免页面加载时的错误 if ( !is_singular('post') ) { return; } $cats = get_the_category(); // 初始化查询变量,防止$cats为空时变量未定义 $the_related_posts = new WP_Query(); if ( $cats ) { $first_category = esc_attr( $cats[0]->term_id ); $args = array( 'cat' => array($first_category), 'post__not_in' => array(get_the_ID()), // 2. 用get_the_ID()替代$post->ID,作用域更可靠 'posts_per_page' => 3, 'ignore_sticky_posts' => true ); $the_related_posts = new WP_Query($args); } // 3. 确保$the_related_posts已初始化,再调用方法 if( $the_related_posts->have_posts() ) : ?> <div class="mt-related-posts"> <div class="wt-container"> <h4 class="widget-title"><?php _e( 'Related Posts', 'magtheme' ); ?></h4> </div> <div class="mtrp-container"> <?php while ($the_related_posts->have_posts()) : $the_related_posts->the_post(); ?> <div class="mt-rel-post"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute();?>"> <?php the_post_thumbnail( 'magtheme-related' ); ?> </a> <h3 class="post-title"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"> <?php echo get_the_title(); ?> </a> </h3> <p class="mt-meta"><?php echo get_the_date(); ?></p> </div> <?php endwhile; wp_reset_postdata(); ?> </div> </div> <?php endif; }
关键修改说明
- 页面类型限制:用
is_singular('post')判断当前是否为单篇文章页面,如果是页面(Pages)或其他类型,直接终止脚本执行,从源头避免错误。 - 变量初始化:在函数开头就把
$the_related_posts初始化为空的WP_Query实例,即使没有分类,后续调用->have_posts()也不会报错。 - 替换
$post->ID:函数内部无法保证$post变量在当前作用域,用get_the_ID()获取当前文章ID更可靠。 - 修复结构问题:原代码里多余的闭合大括号导致逻辑错乱,重新整理了HTML容器的输出逻辑,确保只有存在相关文章时才渲染整个模块。
- 优化日期输出:用
get_the_date()替代the_date(),避免同一日期下多个文章只显示一次日期的问题。
内容的提问来源于stack exchange,提问作者Raashid Din Dar
相关产品推荐
相关产品推荐

