WooCommerce 教程:显示产品子类别

WooCommerce 教程:显示产品子类别

我的客户有一个名为 “品牌” 的类别。每个产品都被分配到特定的品牌子类别,例如耐克,阿迪达斯等。这个任务的目标是在商店/类别/循环页面中显示这样的 “品牌”,以此来帮助用户识别这样的子类别。

WooCommerce 显示产品子类别

在 WooCommerce 循环页面上显示产品子类别


/**
 * @snippet       WooCommerce Show Product Subcategories
 * @sourcecode    https://businessbloomer.com/?p=17525
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 2.4.7
 */

// Create array with product categories that belong to current product

$cats = get_the_terms( $post->ID, 'product_cat' );

if ( ! empty( $cats ) && ! is_wp_error( $cats ) ) {

// Loop through the product categories...

		foreach ( $cats as $term ) {

                        // If parent cat ID = 116 echo subcat name...
			if( $term->parent == 116 ) { echo $term->name; }

		}

		}

代码段 2:在 WooCommerce Shop 页面上显示特定类别

// Add Specific Category ID Under Each Product Title
function show_cat_id() {
global $post;
$cats = get_the_terms( $post->ID, 'product_cat' );
if (count($cats) > 1) {
	foreach ( $cats as $term ) {
		if( $term->term_id == 35 ) { echo $term->name; }
	}
}
}
add_action('woocommerce_after_shop_loop_item_title','show_cat_id', 2);

如何添加此代码?

1 、您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到子主题的 style.css 文件底部)修改之前建议先备份原始文件,若出现错误请先删除此代码。

2 、 WordPress 4.9 后改进了主题编辑器,对于 CSS 代码也可打开网站前台编辑器的【自定义】,复制代码添加到自定义 css 中。

此代码是否可用?

如需帮助或是您有更好的方案想分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。

文章没看懂?代码不会用?需要帮助您可以去论坛提问自助服务台

作者园长

分享关于您的一些信息。可能会被公开。