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

如何在WP_Query循环中获取自定义区块的Testimonial ID并调用对应内容

解决方案

你的核心问题在于混淆了服务器端(PHP)和客户端(HTML/JS)的执行顺序:PHP是在页面输出前执行的,无法读取已经生成的HTML元素属性。正确的做法是在生成带ID的div之前,就直接获取用户指定的Testimonial ID——也就是你自定义区块/短代码接收的参数,直接用它来完成WP_Query查询并输出内容。

实现步骤及代码示例

1. 修正短代码逻辑,直接通过参数获取ID

短代码是连接用户输入和前端输出的核心,你需要让短代码接收id参数,用这个参数直接查询自定义文章类型,同时输出带对应ID的div:

// 注册Testimonial短代码
add_shortcode('testimonial', 'render_testimonial_shortcode');

function render_testimonial_shortcode($atts) {
    // 提取并验证短代码参数
    $atts = shortcode_atts([
        'id' => '',
    ], $atts);

    $testimonial_id = absint($atts['id']);
    if (!$testimonial_id) {
        return '<div class="testimonial-error">请输入有效的Testimonial ID</div>';
    }

    // 执行WP_Query查询指定内容
    $test_query = new WP_Query([
        'post_type'      => 'testimonials',
        'posts_per_page' => 1,
        'p'              => $testimonial_id,
        'post_status'    => 'publish'
    ]);

    ob_start(); // 开启输出缓冲,方便拼接HTML

    if ($test_query->have_posts()) {
        while ($test_query->have_posts()) {
            $test_query->the_post();
            // 输出带指定ID的div和Testimonial内容
            ?>
            <div id="<?php echo esc_attr($testimonial_id); ?>">
                <div class="testimonial-content"><?php the_content(); ?></div>
                <div class="testimonial-author">— <?php the_title(); ?></div>
                <!-- 可添加自定义字段,比如用户职位 -->
                <?php if ($position = get_post_meta(get_the_ID(), 'testimonial_position', true)) : ?>
                    <div class="testimonial-position"><?php echo esc_html($position); ?></div>
                <?php endif; ?>
            </div>
            <?php
        }
        wp_reset_postdata(); // 重置查询,避免影响全局循环
    } else {
        // 未找到内容时的提示
        echo '<div id="' . esc_attr($testimonial_id) . '" class="testimonial-not-found">未找到对应ID的Testimonial</div>';
    }

    return ob_get_clean(); // 返回最终HTML内容
}

2. 调整自定义区块的输出

你的自定义区块应该在用户输入Testimonial ID后,输出带该ID参数的短代码,比如用户输入123,区块就输出:

[testimonial id="123"]

这样短代码执行时,直接通过id参数拿到123,既完成了WP_Query查询,又输出了带id="123"的div,完全不需要事后去读取div的ID。

为什么之前的思路不可行

  • PHP是服务器端脚本,在页面发送到浏览器之前就已经执行完毕,无法读取浏览器端生成的HTML元素属性。
  • JS是客户端脚本,虽然能读取div的ID,但无法直接传递给已经执行完的PHP代码,除非通过AJAX异步请求,但这会增加复杂度,完全没必要。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:00:25