wordpress woocommerce分类分离php代码

brc7rcf0  于 2023-04-11  发布在  WordPress
关注(0)|答案(1)|浏览(113)

下面是我们如何找到WordPress的帖子类别

<?php if (in_category('268')) { ?>
   All articles written here appear in category 268.  
<?php } ?>

我们如何使上述代码woocommerce产品类别?我不能这样做,因为我没有太多的编码知识.谢谢大家到目前为止...
尝试了相关的WordPress和WooCommerce代码,但没有结果

xqkwcwgp

xqkwcwgp1#

试试下面的代码

$categories = get_terms( 'product_cat' ); // Get all WooCommerce product categories
foreach ( $categories as $category ) {
    $category_id = $category->term_id;
    $category_name = $category->name;
    $category_link = get_term_link( $category_id );
    $category_thumbnail = get_woocommerce_term_meta( $category_id, 'thumbnail_id', true );

    // Output the category section
    echo '<div class="category-section">';
    echo '<h2 class="category-title">' . $category_name . '</h2>';

    // Output the products in the current category
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category_id,
                'operator' => 'IN'
            )
        )
    );
    $products = new WP_Query( $args );
    if ( $products->have_posts() ) {
        echo '<ul class="products">';
        while ( $products->have_posts() ) {
            $products->the_post();
            global $product;

            // Output the product details
            echo '<li>';
            echo '<a href="' . get_permalink() . '">';
            echo get_the_post_thumbnail( $product->get_id(), 'thumbnail' );
            echo '<h3>' . get_the_title() . '</h3>';
            echo '<span class="price">' . $product->get_price_html() . '</span>';
            echo '</a>';
            echo '</li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    }

    echo '</div>';
}

这段代码将遍历所有WooCommerce产品类别,并在其各自的部分中输出每个类别,并在标题中显示类别名称。然后,它将查询属于当前类别的所有产品,并将它们显示在无序列表中,并显示其各自的详细信息。

相关问题