drs7798 2014-01-24 12:51
浏览 48
已采纳

WooCommerce在产品循环中将产品类别添加为类

i'm working on a small Woocommerce shop, and i would like to have a sorting function. 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. How is this done?

  • 写回答

1条回答 默认 最新

  • douchuanghan1344 2014-09-24 19:06
    关注

    Those classes are generated by the WordPress post_class() function as seen in the content-product.php template:

    <li <?php post_class( $classes ); ?>>
    

    There's a good example in the Codex on how to add categories to the post class. 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' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用