首页 > 解决方案 > 使用 wp 查询获取所有 woocommerce 类别?

问题描述

我想获取所有带有标题和图像的 woocommerce 类别。之后,我想在首页上展示它们。避免 foreach 循环,因为我的首页设计类似于这样。[在此处输入图片描述][1]

                <?php


$termSlug = array();
$tax_terms = get_terms('product_cat', array('hide_empty' => '0'));      
foreach ( $tax_terms as $tax_term ):
  $termSlug[] = $tax_term->slug;   
endforeach;

$args = array(
        'post_type' => 'product',  //Post type event  
        'posts_per_page' => -1,

        'tax_query'     => array(
                array(
                    'taxonomy'  => 'product_cat',
                    'field'     => 'slug', 
                    'terms'     => $termSlug
                )
            )

);

 // The Query
$the_query = new WP_Query( $args );
//echo '<pre>';print_r($the_query);echo "</pre>";

if ( $the_query->have_posts() ) {

        while ( $the_query->have_posts() ) {
           $the_query->the_post();

                 ?>    
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#fff'>Nothing Found</h2>
        </div>
<?php } echo '</div>';?>


  [1]: https://i.stack.imgur.com/A98em.jpg

标签: phpwordpresswoocommerce

解决方案


以下代码段将在 WooCommerce 中获取产品类别。获取类别后,它将循环显示类别名称以及链接和类别图像。

$product_categories = get_terms( 'product_cat', 'hide_empty=0' );
if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
    foreach ( $product_categories as $category ) {
        ?>
        <div class="category-item">
            <h4><a href="<?php echo esc_url( get_term_link( $category ) ); ?>"><?php echo esc_html( $category->name ); ?></a></h4>
            <?php
            $thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
            $image = wp_get_attachment_url( $thumbnail_id );
            ?>
            <?php if ( $image ) : ?>
                <img src="<?php echo esc_url( $image ); ?>" alt="" />
            <?php endif; ?>
        </div>
        <?php
    }
}

推荐阅读