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

如何将自定义分类法术语名称作为get_posts查询的meta_value

问题分析与解决方案

你的问题出在get_the_term_list的返回值上——这个函数生成的是带HTML链接的逗号分隔字符串,比如<a href="...">101</a>, <a href="...">102</a>,而不是纯的路线编号数组。直接把这个字符串传给meta_value,自然没法和walks帖子里单个存储的route_number精确匹配,所以查不到结果。

修复代码

替换原来的变量获取和查询逻辑,改用get_the_terms获取纯术语对象,提取编号后用IN条件查询:

// 获取当前feature关联的所有route-number术语
$terms = get_the_terms( $post->ID, 'feature-on-route-number' );
$route_numbers = array();

// 处理术语数组,提取编号(假设术语的name就是路线编号,用slug的话改成$term->slug)
if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        $route_numbers[] = $term->name;
    }
}

// 只有当有有效编号时才执行查询
if ( ! empty( $route_numbers ) ) {
    $posts = get_posts(array(
        'posts_per_page' => -1,
        'post_type'      => 'walks',
        'meta_query'     => array(
            array(
                'key'     => 'route_number',
                'value'   => $route_numbers,
                'compare' => 'IN' // 匹配数组中任意一个值
            )
        )
    ));

    // 后续处理查询结果
}

关键说明

  1. get_the_terms返回的是术语对象数组,能直接提取到纯编号值,避免HTML干扰
  2. 使用meta_query的IN比较符,可以一次性匹配所有关联的路线编号,不用循环单个查询
  3. 增加了空值判断,避免没有关联术语时执行无效查询

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:31:05