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

如何在自定义文章类型单页匹配文章标签查询展示关联产品

问题排查与修复方案

现有代码问题

  • get_the_tags() 返回值为WP_Term对象数组,不是标签名称字符串,直接传入查询参数无法被识别
  • WP_Query 没有原生的title查询参数,原有查询条件不生效,导致返回所有产品的默认排序结果
  • 没有添加返回条数限制,不符合仅返回1个匹配产品的需求

修复后代码

<?php 
// 查询当前文章关联产品
$current_article_tags = get_the_tags();

// 仅当文章存在标签时执行查询
if ($current_article_tags) {
    // 提取所有标签名称组成数组
    $tag_names = wp_list_pluck($current_article_tags, 'name');

    $related_products = new WP_Query(array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'post_title__in' => $tag_names, // 精确匹配产品标题与标签名称
        'posts_per_page' => 1, // 仅返回1条结果
        'no_found_rows'  => true, // 不需要分页时优化查询性能
    ));

    if ($related_products->have_posts()) {
        while($related_products->have_posts()) {
            $related_products->the_post();
            // 输出产品标题,加转义保证安全
            echo esc_html(get_the_title());
        }
        wp_reset_postdata();
    }
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 20:54:01