How to get WooCommerce Product Category Link by ID?
-
19-04-2021 - |
Вопрос
WooCommerce's product categories are a custom taxonomy called product_cat
. In a function I'm writing, I'm using get_categories
with the taxonomy
parameter set to product_cat
. Everything works fine and I can get the term id, the name, and even the slug. What I can't figure out is how to get the link to display. Apparently get_category_link
doesn't work with custom taxonomy and get_term_link
isn't working either, I get an error. Here's what I have:
$prod_cat_args = array(
'taxonomy' => 'product_cat', //woocommerce
'orderby' => 'name',
'empty' => 0
);
$woo_categories = get_categories( $prod_cat_args );
foreach ( $woo_categories as $woo_cat ) {
$woo_cat_id = $woo_cat->term_id; //category ID
$woo_cat_name = $woo_cat->name; //category name
$return .= '<a href="' . get_category_link( $woo_cat_id ) . '">' . $woo_cat_name . '</a>';
}//end of $woo_categories foreach
Suggestions?
Решение
Another update (Sept. 2015):
I can use get_term_link
after all. The problem was that the string needed to be converted to an integer. Used a Stack Overflow tip for the fastest way to convert it using the (int)$value in PHP.
So it would look like this if you don't want to use the slug in the foreach loop:
$woo_cat_id_int = (int)$woo_cat_id; //convert
That converted value is used instead of the slug in get_term_link
. Hope it helps someone. :-)
Looks like I figured it out.
I used get_term_link. And I was getting an error because I was using it this way:
get_term_link( $woo_cat_id, 'product_cat' );
Which gave me this error:
Object of class WP_Error could not be converted to string
So I went this route instead with the slug
and it worked:
$prod_cat_args = array(
'taxonomy' => 'product_cat', //woocommerce
'orderby' => 'name',
'empty' => 0
);
$woo_categories = get_categories( $prod_cat_args );
foreach ( $woo_categories as $woo_cat ) {
$woo_cat_id = $woo_cat->term_id; //category ID
$woo_cat_name = $woo_cat->name; //category name
$woo_cat_slug = $woo_cat->slug; //category slug
$return .= '<a href="' . get_term_link( $woo_cat_slug, 'product_cat' ) . '">' . $woo_cat_name . '</a>';
}//end of $woo_categories foreach
Другие советы
Thanks, I use
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
}
It works perfectly.
$prod_cat_args = array(
'taxonomy' => 'product_cat', //woocommerce
'orderby' => 'name',
'empty' => 0
);
$terms = get_categories( $prod_cat_args );
//$term_id=6;
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
echo '<li><a class="shopping-now" href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
}
get_term_link()
does work smoothly, when using the object returned by get_categories()
.