注意:尝试获取非对象的属性
那是因为$cat_parents
不是object
; 这是一个array
:
$cat_parents_url = get_category_link($cat_parents->term_id);
其次,要仅获取类别URL,请调用
get_category_parents()
将第二个参数设置为
false
, 像这样:
$get_cat_parents = rtrim(get_category_parents($last_category->term_id, false, \',\'),\',\');
$get_cat_parents
然后是一个列表/
string
,而不是HTML格式的类别链接,例如
<a href="http://example.com/category/slug">Name of the category here</a>
.
然后,在foreach
循环,您可以按如下方式获取类别URL:
foreach($cat_parents as $slug) {
$term = get_category_by_slug( $slug );
if ( ! $term ) {
continue;
}
$cat_url = esc_url( get_category_link( $term->term_id ) );
...
}
即获取类别/术语
object
/数据使用
get_category_by_slug()
, 然后使用
get_category_link()
.
以下是我使用的完整代码:(为了清晰起见,重新缩进)
// Get post category info
$category = get_the_category();
if(!empty($category)) {
// Get last category post is in
$last_category = $category[count($category) - 1];
// Get parent any categories and create array
$get_cat_parents = rtrim(get_category_parents($last_category->term_id, false, \',\'),\',\');
$cat_parents = explode(\',\',$get_cat_parents);
$cat_display = \'\';
$separator = \', \'; // not defined; so I defined it here.
$counter = 0; // not defined; so I defined it here.
foreach($cat_parents as $slug) {
$term = get_category_by_slug( $slug );
if ( ! $term ) {
continue;
}
$cat_url = esc_url( get_category_link( $term->term_id ) );
$cat_display .= \'<li class="item-cat" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><span itemprop="item"><span itemprop="name">\'.$cat_url .\'</span></span><meta itemprop="position" content="\'. $counter++ .\'" /></li>\';
$cat_display .= \'<li class="separator"> \' . $separator . \' </li>\';
}
echo $cat_display; // test
}