Notice: Trying to get property of non-object
That’s because $cat_parents
is not an object
; it’s an array
:
$cat_parents_url = get_category_link($cat_parents->term_id);
Secondly, to get just the category URL, call get_category_parents()
with the second parameter set to false
, like so:
$get_cat_parents = rtrim(get_category_parents($last_category->term_id, false, ','),',');
$get_cat_parents
would then be a list/string
of category slugs and not category links in HTML format such as <a href="http://example.com/category/slug">Name of the category here</a>
.
Then, in the foreach
loop, you can get the category URL like so:
foreach($cat_parents as $slug) {
$term = get_category_by_slug( $slug );
if ( ! $term ) {
continue;
}
$cat_url = esc_url( get_category_link( $term->term_id ) );
...
}
I.e. Get the category/term object
/data using get_category_by_slug()
, and then the category URL using get_category_link()
.
Here’s the full code I used: (re-indented for clarity)
// 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
}