首页 > 解决方案 > Woocommerce - 在普通页面上添加自定义类别类

问题描述

我正在尝试将自定义类添加到普通页面上的特定产品类别。

以下 php 在商店存档页面上运行良好,但我还在首页(畅销书)和其他页面上显示了产品,并且还希望添加自定义类。

我正在使用 elementor 及其“产品”小部件和 hello 主题。

function filter_woocommerce_post_class( $classes, $product ) {  
    // Returns true when viewing a product category archive.
    if ( is_shop() ) {
        // Set taxonmy
        $taxonomy = 'product_cat';
        
        // Get the terms
        $terms = get_the_terms( $product->get_id(), $taxonomy );
        
        // Error or empty
        if ( is_wp_error( $terms ) || empty( $terms ) ) {
            return $classes;
        }
        
        // Loop trough
        foreach ( $terms as $index => $term ) {
            // Product tag Id
            $term_id = $term->term_id;
            
            // Add new class
            $classes[] = 'product-in-cat-' . $term_id;
        }
    }
    
    return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );

标签: phpwordpresswoocommerce

解决方案


推荐阅读