Reputation: 23
I was working on adding the product categories to under the shop image on my site. I have it working using the code below, but the categories do not have spaces between them. I am a bit of a novice here so wondered if someone can help me where I could add a space of comma between each category listing that would be great! Thanks in advance.
add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 1 );
function after_shop_loop_item_title() {
global $post;
$terms = get_the_terms( $post->ID, 'videocategories' );
$text = "<h3>Category: ";
foreach ($terms as $term) {
$text .= $term->name;
}
$text .= "</h3>";
echo $text;
}
Upvotes: 2
Views: 329
Reputation: 3116
You can use the PHP implode()
function. This will create a string from an array and separate them with a separator of your choosing.
In the example below I first created an array of the categories and then used the implode()
function in combination with the printf()
function to print a comma separated list enclosed by h3
tags:
add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 10 );
function after_shop_loop_item_title() {
global $post;
$terms = get_the_terms( $post->ID, 'videocategories' );
$product_cats = array();
if ( !empty( $terms ) ) {
// Get an array of the categories
foreach ( $terms as $key => $term ) {
$product_cats[] = sprintf( '<a href="%s">%s</a>', get_term_link( $term->slug, 'videocategories' ), $term->name );
}
// Convert product category array into comma separated string
printf( '<h3>Category: %s</h3>', implode( ', ', $product_cats ) );
}
}
Upvotes: 1