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

如何在GeneratePress钩子中为AAWP短码传入WordPress分类变量

问题:GeneratePress钩子中传递分类变量到AAWP短码的bestseller参数

我用WordPress搭配GeneratePress主题,利用主题Elements功能在钩子中执行PHP代码,想通过AAWP插件展示对应分类的亚马逊畅销榜单——获取当前WordPress分类,把分类名传入AAWP短码的bestseller参数。

尝试了两种写法都有问题:
第一种代码:

<?php
$categories = get_the_category();

if ( ! empty($categories ) ) {
    $category = $categories[0];
    $name = $category->name;
    $bestseller = 'bestseller="'.$name.'"';
    $shortCode = '[aawp grid="3" '.$bestseller.' items="3" filter_items="20" orderby="percentage_saved" order="desc"]';
    
echo do_shortcode($shortCode); 
}
?>

页面完全不显示榜单,换成硬编码参数就能正常显示,推测是bestseller参数未被正确识别。

第二种代码:

<?php
$categories = get_the_category();

if ( ! empty($categories ) ) {
    $category = $categories[0];
    $name = $category->name;
    $bestseller = 'bestseller="'.$name.'"';
    $shortCode = '[aawp template="angebot-vertical" grid="3" bestseller="'.$name.'" items="3" filter_items="20" orderby="percentage_saved" order="desc"]';
    
echo do_shortcode($shortCode); 
}
?>

能显示随机产品,但bestseller参数的变量值没被读取,相当于空参数触发的默认展示。


核心问题分析

get_the_category()是针对单篇文章获取分类的,如果在分类归档页面(比如分类列表页)使用这个钩子,该函数无法正确获取当前分类——它只会返回页面内第一篇文章的分类,甚至可能返回空。

修正方案

根据页面类型选择正确的分类获取方式,同时优化短码拼接逻辑:

通用修正代码

<?php
// 判断当前页面类型,获取正确的分类对象
if (is_category()) {
    // 分类归档页面
    $current_category = get_queried_object();
} elseif (is_single()) {
    // 单文章页面
    $categories = get_the_category();
    $current_category = !empty($categories) ? $categories[0] : null;
} else {
    // 其他页面(如首页、标签页),可根据需求调整逻辑
    $current_category = null;
}

if ($current_category && !empty($current_category->name)) {
    // 用sprintf拼接短码,避免手动转义出错
    echo do_shortcode(sprintf(
        '[aawp grid="3" bestseller="%s" items="3" filter_items="20" orderby="percentage_saved" order="desc"]',
        esc_attr($current_category->name)
    ));
}
?>

关键优化点

  • 区分分类页和文章页,用get_queried_object()确保分类归档页能拿到当前分类
  • 用sprintf()拼接短码,避免手动字符串拼接时的引号转义错误
  • 用esc_attr()对分类名转义,防止特殊字符破坏短码结构
  • 增加场景判断,覆盖分类页和文章页的使用需求

额外验证步骤

  1. 确认钩子位置匹配页面类型(比如分类页用generate_before_main_content这类钩子)
  2. 可以临时添加var_dump($current_category);查看分类对象是否正确获取,确认后再移除
  3. 确保AAWP插件已配置好亚马逊API,且分类名和亚马逊bestseller分类关键词完全匹配(注意大小写、空格等细节,AAWP对参数值匹配严格)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:55:42