【问题标题】:How to detect the slug of the Category page i'm on? (WooCommerce)如何检测我所在的类别页面的 slug? (WooCommerce)
【发布时间】:2014-03-18 18:27:18
【问题描述】:

我一直在寻找有关列出 Internet 上所有 slug 的教程,但似乎找不到可以回显/返回我所在类别的 slug 的函数或代码行,因此我可以将其保存在变量中。

有人知道它是什么吗? 我需要能够在 archive-product.php 中使用它

提前致谢

【问题讨论】:

    标签: php wordpress loops woocommerce slug


    【解决方案1】:

    类别 slug 应该在全局变量 $wp_query 中可用。

    yourtheme/woocommerce/archive-product.php 中试试这个:

    global $wp_query;
    $cat_slug = $wp_query->query_vars['product_cat'];
    echo $cat_slug;
    

    get_the_category() 的另一种方法可能适用于 archive.php 中的普通帖子,但我在 archive-product.php 中没有成功。

    【讨论】:

    • 如果您想要产品类别 ID(而不是 slug),请参阅 wordpress.stackexchange.com/a/198425/11807
    • 好答案。在最后一个版本的 woocommerce 中,我可以确认它仍然有效的唯一解决方案。非常感谢!
    【解决方案2】:
    $slugs = array();
    foreach( (get_the_category()) as $category ) { 
        array_push( $slugs, $category->slug );
    } 
    var_dump( $slugs );
    

    (未经测试)

    http://codex.wordpress.org/Function_Reference/get_the_category

    编辑:

    经过测试并且可以正常工作。尝试添加到 archive.php(暂时)并确保您的 url 类似于:mysite.com/category/uncategorized/。我怀疑您可能没有调用正确的模板文件,或者实际上可能没有浏览任何类别。

    【讨论】:

    • 这在我的情况下不起作用。我得到一个空数组。也许这在较新版本的 woocommerce 中有所改变。由于这个问题有很多次访问,您能否更新答案或确认这是否仍然有效?非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2015-09-18
    • 2019-10-18
    • 2016-11-21
    • 2014-09-15
    • 2022-11-21
    • 2021-10-14
    相关资源
    最近更新 更多