从永久链接Wordpress获取多个类别名称

问题描述

我正在尝试获取永久链接中可用类别的类别名称。例如我具有以下永久链接结构。

abc.com/product-category/category-1/category-2/

category-1 category-2 均为类别。当我尝试$wp_query->get_queried_object()时,它只会向我返回与 category-2 相关的信息。如何使用任何现有的wordpress函数获取 category-1 的详细信息?

谢谢

解决方法

由于以前的类别是当前用法的父项,因此可以使用get_term https://developer.wordpress.org/reference/functions/get_term/进行获取 $ child_category = $ wp_query-> get_queried_object(); $ parent_category = get_term($ child_category-> parent,'product-category');

,

您可以使用category-2函数获得get_term的父级。

$child_term = get_queried_object();
$parent_term = get_term($child_term->parent,'product_cat'); // if your using Woocommerce then the taxonomy is called 'product_cat'

这两个变量都是WP_Term对象。

https://developer.wordpress.org/reference/classes/wp_term/

您可以从那里访问名称,ID和所需的任何其他信息。

修订版

如果您要创建自定义类别页面(即不是Woocommerce / WordPress页面),那么我建议向页面编辑器添加meta-box

https://developer.wordpress.org/reference/functions/add_meta_box/

https://www.advancedcustomfields.com/

有一个带有您产品类别的选择框。

https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/

然后在页面模板中,将term(s) ID用作WP_Query的一部分,以从这两个产品类别中提取产品。