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

如何获取两个不同自定义字段值相同的WordPress文章?

实现需求的修正代码

要获取当前文章以外、answer自定义字段值等于当前文章close_answer_1值的文章列表,修正后的WP_Query代码如下:

<?php
// 获取当前文章的close_answer_1字段值
$current_close_val = get_post_meta(get_the_ID(), 'close_answer_1', true);

// 构建查询参数
$args = array(
    'posts_per_page' => -1,
    'post__not_in'   => array(get_the_ID()), // 排除当前文章
    'meta_query'     => array(
        array(
            'key'     => 'answer',
            'value'   => $current_close_val,
            'compare' => '='
        )
    )
);
$matched_posts_query = new WP_Query($args);

// 遍历输出匹配的文章
if ($matched_posts_query->have_posts()) {
    while ($matched_posts_query->have_posts()) {
        $matched_posts_query->the_post();
        // 按需输出文章内容,示例:标题+链接
        printf('<h3><a href="%s">%s</a></h3>', get_permalink(), get_the_title());
    }
    wp_reset_postdata(); // 重置查询上下文
} else {
    echo '未找到符合条件的文章';
}
?>

原代码的问题分析

  • 逻辑错误:原代码使用relation => 'OR',会同时抓取close_answer_1=INSET(包含当前文章)和answer=INSET的文章,不符合“仅其他文章且answer字段匹配”的需求。
  • 缺少过滤规则:没有排除当前文章的参数,必须通过post__not_in过滤当前文章ID,避免结果包含自身。
  • 冗余查询:不需要同时查询两个字段,仅需精准匹配answer字段即可。

内容的提问来源于stack exchange,提问作者Patrick A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:05:07