You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中while循环自定义文章类型时the_ID()输出异常修复求助

问题原因

the_ID() 函数的特性是直接输出当前文章的ID,而非返回ID字符串。当你在字符串拼接(比如 id="panelsStayOpen-heading'.the_ID().'")中使用它时,PHP会优先执行 the_ID() 把ID输出到页面,再处理剩余的属性字符串,导致ID跑到了属性值外部。

解决方法

把代码中的 the_ID() 替换为 get_the_ID()——这个函数会返回当前文章的ID字符串,不会直接输出,能完美嵌入到属性值的拼接逻辑里。

错误代码示例

<?php
$faq_query = new WP_Query(['post_type' => 'advance_faq', 'posts_per_page' => -1]);
if ($faq_query->have_posts()) :
    while ($faq_query->have_posts()) : $faq_query->the_post();
?>
<div class="faq-panel">
  <h3 id="panelsStayOpen-heading'.the_ID().'">
    <?php the_title(); ?>
  </h3>
</div>
<?php
    endwhile;
    wp_reset_postdata();
endif;
?>

修正后的代码示例

<?php
$faq_query = new WP_Query(['post_type' => 'advance_faq', 'posts_per_page' => -1]);
if ($faq_query->have_posts()) :
    while ($faq_query->have_posts()) : $faq_query->the_post();
?>
<div class="faq-panel">
  <!-- 写法1:直接嵌入PHP输出 -->
  <h3 id="panelsStayOpen-heading<?php echo get_the_ID(); ?>">
    <?php the_title(); ?>
  </h3>
  <!-- 写法2:字符串拼接(双引号可直接嵌入变量) -->
  <h3 id="<?php echo "panelsStayOpen-heading" . get_the_ID(); ?>">
    <?php the_title(); ?>
  </h3>
</div>
<?php
    endwhile;
    wp_reset_postdata();
endif;
?>
补充说明
  • get_the_ID() 返回的是整数类型ID,PHP在字符串拼接时会自动转换为字符串,无需额外处理。
  • 循环结束后务必调用 wp_reset_postdata(),恢复全局 $post 变量,避免影响后续的WordPress查询逻辑。

内容的提问来源于stack exchange,提问作者Elvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:10:29