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

如何构建WP_Query嵌套元查询获取当前用户的所有appointment?

获取当前登录用户的所有Appointment

要实现需求,核心逻辑是先拿到当前用户关联的所有vendor ID,再用这些ID筛选出关联的appointment,具体代码实现如下:

步骤1:获取当前用户关联的Vendor ID

// 仅处理已登录用户
if (is_user_logged_in()) {
    $current_user_id = get_current_user_id();
    // 获取用户关联的所有vendor ID(false表示返回数组,兼容多vendor关联场景)
    $vendor_ids = get_user_meta($current_user_id, 'user_vendor', false);
    
    // 无关联vendor时直接返回空结果
    if (empty($vendor_ids)) {
        $appointments = new WP_Query(['post_type' => 'appointment', 'posts_per_page' => 0]);
    }
} else {
    // 未登录用户返回空结果
    $appointments = new WP_Query(['post_type' => 'appointment', 'posts_per_page' => 0]);
}

步骤2:查询关联的Appointment

// 存在关联vendor时执行查询
if (!empty($vendor_ids)) {
    $args = [
        'post_type' => 'appointment',
        'posts_per_page' => -1, // 获取所有匹配结果,可按需调整数量
        'meta_query' => [
            [
                'key' => 'vendor_solution',
                'value' => $vendor_ids,
                'compare' => 'IN', // 匹配数组中的任意一个vendor ID
                'type' => 'NUMERIC' // 假设字段存储的是数字ID,根据实际存储格式调整
            ]
        ]
    ];

    $appointments = new WP_Query($args);
}

// 遍历输出结果
if ($appointments->have_posts()) {
    while ($appointments->have_posts()) {
        $appointments->the_post();
        // 输出预约信息示例
        echo '<h3>' . get_the_title() . '</h3>';
        // 可额外输出关联的vendor信息
        $linked_vendor = get_post(get_post_meta(get_the_ID(), 'vendor_solution', true));
        if ($linked_vendor) {
            echo '<p>关联商家:' . $linked_vendor->post_title . '</p>';
        }
    }
    wp_reset_postdata();
} else {
    echo '<p>暂无相关预约记录</p>';
}

注意事项

  • 如果user_vendor字段仅存储单个vendor ID,可将get_user_meta的第三个参数改为true,但保留false能兼容多vendor关联的扩展场景。
  • 若vendor_solution字段存储的是序列化数组而非纯ID,需将compare改为LIKE,但不建议用序列化存储,纯ID查询效率更高且更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:55:16