php - 在商店图片下方添加 Woocommerce 类别
问题描述
我正在努力将产品类别添加到我网站上的商店图片下。我使用下面的代码让它工作,但类别之间没有空格。我在这里有点新手,所以想知道是否有人可以帮助我,我可以在每个类别列表之间添加一个逗号空格,这会很棒!提前致谢。
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;
}
解决方案
您可以使用 PHPimplode()
函数。这将从数组中创建一个字符串,并使用您选择的分隔符将它们分开。
在下面的示例中,我首先创建了一个类别数组,然后将该implode()
函数与该函数结合使用以打印由标签printf()
包围的逗号分隔列表:h3
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 ) );
}
}
推荐阅读
- flutter - Flutter Windows:文本字段不允许空间
- c# - 如何在gridview中检查不同行中的数据
- angular - '--module' 选项的参数必须是:'none'、'commonjs'、'amd'、'system'、'umd'、'es6'、'es2015'、'esnext'
- postgresql - 如何在 Postgresql 上压缩/解压缩数据字节
- logging - GCP 操作系统补丁管理日志记录
- android - 定期后台同步在 PWA 上不起作用 - 官方 API 演示已损坏
- node.js - 如何使用带有多个过滤器的猫鼬分页 v2
- arrays - 如何在 OpenRefine 中过滤大量 JSON?
- database - 对于 10 万条记录,是否可以提高 Room 数据库中的行更新速度?
- excel - 使用宏的带有通配符的高级自动过滤器的语法问题