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

如何将自定义字段的多页面ID传入WordPress循环的post__in参数?

问题原因

你当前代码里的get_post_meta(get_the_ID(),'key', true)第三个参数传了true,这会让函数返回单个值——如果你的自定义字段里输入的是逗号分隔的多个ID(比如12,34,56),这里只会拿到整个字符串,而array($pageid)会把这个字符串当成数组的单个元素,WP_Query解析时只会识别第一个有效ID,所以只返回第一个页面。

解决方法

需要把自定义字段里的ID字符串转换成整数数组,才能正确传给post__in参数,具体修改如下:

修改后的完整代码

<?php 
// 获取自定义字段的ID字符串
$page_ids_str = get_post_meta(get_the_ID(), 'key', true);

// 处理字符串:分割为数组、转成整数、过滤空值
$page_ids = array_map('intval', array_filter(explode(',', $page_ids_str)));

// 只有当ID数组不为空时,才执行查询
if (!empty($page_ids)) {
    $args = array(
        'post_type' => 'page', 
        'post__in' => $page_ids,
        'posts_per_page' => -1, // 确保返回所有指定ID的页面
        'orderby' => 'post__in' // 保持ID输入的顺序
    );

    $childrens = new WP_Query($args);
    
    if ($childrens->have_posts()) : ?>
     <div class="sidebar-post-container">
        <?php while ($childrens->have_posts()) : $childrens->the_post();?>
    
            <div class="staff-thumbnail" id="staff-<?php the_ID(); ?>">
                <figure id="attachement_<?php the_ID();?>">
                    <?php the_post_thumbnail(array(200,200,true),array('loading' => 'lazy', "alt"=> '', 'aria-hidden'=> 'true', 'tabindex' =>"-1"));?>
                </figure>
    
                <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
    
            </div>
    
        <?php endwhile; ?>
    </div>
    <?php 
    endif; 
    wp_reset_postdata(); // 推荐用wp_reset_postdata()替代wp_reset_query(),更贴合WP_Query的使用场景
}
?>

关键修改点说明

  • 分割字符串为数组:用explode(',', $page_ids_str)把逗号分隔的字符串拆成独立数组元素
  • 转换为整数:array_map('intval', ...)确保每个元素都是整数,避免WP_Query解析出错
  • 过滤空值:array_filter(...)去掉用户输入时可能产生的多余空元素(比如末尾多打了逗号)
  • 新增orderby => 'post__in':让返回的页面顺序和你输入ID的顺序完全一致
  • 新增posts_per_page => -1:确保返回所有指定的页面,不会被默认分页限制截断
  • 替换wp_reset_query()为wp_reset_postdata():这是使用WP_Query后恢复全局$post变量的标准方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:46:09