[英]WooCommerce adding product categories as class in product loop
i'm working on a small Woocommerce shop, and i would like to have a sorting function. 我正在一家小型Woocommerce商店工作,我想具有分类功能。 The sorting works like a charm, but it is sorting based on the products class. 排序的工作方式就像一个超级按钮,但是它是根据产品类别进行排序的。 So i would like to post the product category as class on the list item in my product loop. 所以我想将产品类别作为类发布到我的产品循环中的列表项中。 My loop looks like this: 我的循环如下所示:
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 999
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile;
}
else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
It outputs list items for each item like this: 它为每个项目输出列表项目,如下所示:
<li class="post-15 product type-product status-publish hentry first instock">
<a href="http://shop.bbpixelz.dk/product/i-phone-ai-template/">
<img width="150" height="150" src="http://shop.bbpixelz.dk/wp-content/uploads/2014/01/iphone-ai-template-150x150.png" class="attachment-shop_catalog wp-post-image" alt="iphone-ai-template">
<h3>I-Phone Vector Template</h3>
<span class="price"><span class="amount">$2</span></span>
</a>
<a href="/?add-to-cart=15" rel="nofollow" data-product_id="15" data-product_sku="ai-iphone" class="add_to_cart_button button product_type_simple">Add to cart</a>
</li>
I want to add the product category as a class to the li. 我想将产品类别添加为li。 How is this done? 怎么做?
Those classes are generated by the WordPress post_class()
function as seen in the content-product.php
template: 这些类由WordPress post_class()
函数生成,如content-product.php
模板所示:
<li <?php post_class( $classes ); ?>>
There's a good example in the Codex on how to add categories to the post class. 在Codex中有一个很好的例子,说明如何向post类添加类别。 Modifying that a bit for product categories we have: 对产品类别进行一些修改:
// add product category name to post class
function category_id_class( $classes ) {
global $post;
$product_cats = get_the_terms( $post->ID, 'product_cat' );
if( $product_cats ) foreach ( $product_cats as $category ) {
$classes[] = $category->name;
}
return $classes;
}
add_filter( 'post_class', 'category_id_class' );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.