如何获取分类法下最近5篇文章信息并填充Schema的makesOffer字段
实现步骤
- 先在Schema输出逻辑前,通过WordPress内置查询函数拉取当前品牌分类下的5篇已发布优惠券文章
- 循环遍历文章列表,将文章的标题、链接、摘要、有效期自动映射到
Offer结构化数据的对应字段 - 放弃直接在JSON字符串里嵌入PHP输出的写法,改用「先构建PHP数组→统一JSON编码输出」的模式,避免因为内容里的特殊字符(比如双引号)打断JSON格式
具体代码调整
第一步:提前查询分类下的优惠券文章
在原有代码最开头加入文章查询逻辑,自动识别当前品牌分类的ID,不需要硬写:
// 自动获取当前品牌店铺分类的ID $current_term_id = get_queried_object_id(); $makes_offer_list = []; // 拉取当前分类下的5篇已发布文章 $coupon_posts = get_posts([ 'numberposts' => 5, 'post_status' => 'publish', // 如果你的优惠券是自定义文章类型,在这里补充 'post_type' => 'coupon' 'tax_query' => [ [ 'taxonomy' => '替换为你实际的品牌分类法slug', // 比如你给亚马逊分类注册时的分类法标识 'field' => 'term_id', 'terms' => $current_term_id ] ] ]); // 循环生成Offer结构 foreach ($coupon_posts as $post_item) { setup_postdata($post_item); // 读取文章关联的优惠券有效期自定义字段,没有的话用文章发布时间兜底 $valid_from = get_post_meta($post_item->ID, '优惠券生效时间字段名', true) ?: get_the_date('c', $post_item); $valid_through = get_post_meta($post_item->ID, '优惠券过期时间字段名', true) ?: ''; $makes_offer_list[] = [ '@type' => 'Offer', 'name' => get_the_title($post_item), // 自动取文章标题 'url' => get_permalink($post_item), // 自动取文章永久链接 'description' => wp_trim_words(get_the_excerpt($post_item), 30), // 自动取文章摘要作为优惠描述 'validFrom' => $valid_from, 'validThrough' => $valid_through ]; } wp_reset_postdata();
第二步:替换原有Schema输出逻辑
原来直接把PHP echo嵌在JSON字符串里的写法容错率极低,只要文章标题里有双引号就会导致Schema失效。建议把整个结构先写成PHP关联数组,最后统一编码输出,把原来的<script>标签内的内容替换为:
<script type="application/ld+json"> <?php $schema_config = [ '@context' => 'http://schema.org', '@graph' => [ [ '@type' => 'WebPage', 'url' => esc_html($taglink), 'image' => [ '@type' => 'ImageObject', 'url' => esc_html($brandimage), 'height' => 100, 'width' => 170 ], 'publisher' => [ '@type' => 'Organization', 'name' => 'Coupon.com', 'logo' => [ '@type' => 'ImageObject', 'url' => 'https://cdn.coupontac.com/ovowhakr/2020/10/Logo.png.webp', 'width' => 500, 'height' => 200 ] ], 'dateModified' => get_the_modified_date('c', $post), 'description' => esc_html($schemdesc2), 'headline' => esc_html($heading), 'mainEntity' => [ '@type' => 'Store', 'name' => esc_html($tagname), 'image' => esc_html($brandimage), 'sameAs' => esc_html($weburl), 'aggregateRating' => [ '@type' => 'AggregateRating', 'ratingValue' => esc_html($userrating), 'ratingCount' => esc_html($ratingcount), 'bestRating' => 5, 'worstRating' => 0 ], 'description' => esc_html($schemdesc), // 直接把之前循环生成的Offer列表塞进来,替换原来的空数组 'makesOffer' => $makes_offer_list ] ] ] ]; // 统一编码输出,自动处理特殊字符转义 echo json_encode($schema_config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?> </script>
注意事项
- 代码里标注了「替换」的部分,要改成你网站实际使用的分类法slug、自定义字段名,不要直接复制占位符
- 只要分类下发布了新的符合条件的优惠券文章,Schema会自动拉取,不需要手动修改代码
- 可以通过Google的结构化数据测试工具验证输出是否符合规范,不需要手动检查JSON格式
内容的提问来源于stack exchange,提问作者Jack White
相关产品推荐
相关产品推荐

