显示4首产品属性

时间:2020-04-21 19:06:36

标签: woocommerce hook-woocommerce

我想在每个产品卡上显示前4个产品属性。 该代码仅向我显示特定属性。有什么办法获取这些属性?每个类别都有自己的属性,因此我无法为网站上的每个类别都做。请帮助我

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

$has_row    = false;
$attributes = $product->get_attributes();

ob_start();

?>
<div class="product_attributes">

    <?php foreach ( $attributes as $attribute ) :

        if ( empty( $attribute['is_visible'] ) || ( $attribute['is_taxonomy'] && ! taxonomy_exists( $attribute['name'] ) ) ) 
            continue;

        $values = wc_get_product_terms( $product->get_id(), $attribute['name'], array( 'fields' => 'names' ) );
        $att_val = apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );

        if( empty( $att_val ) )
            continue;

        $has_row = true;
        ?>

    <div class="col">
        <div class="att_label"><?php echo wc_attribute_label( $attribute['name'] ); ?></div>
        <div class="att_value"><?php echo $att_val; ?></div><!-- .att_value -->
    </div><!-- .col -->

    <?php endforeach; ?>

</div><!-- .product_attributes -->
<?php
if ( $has_row ) {
    echo ob_get_clean();
} else {
    ob_end_clean();
}

1 个答案:

答案 0 :(得分:0)

所以我写了其他函数:

if( $_product->has_attributes() ){
    // Initializing
    $attributes = array(); 
    // Loop through product attributes
    $i = 0;
    foreach( $_product->get_attributes() as $taxonomy => $attribute ){
        // The product attribute label name

        $attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;

        // Set each product attribute with its values in an array

        // $attributes[] = '<strong>'.$attribute_name.'</strong>: '.$_product->get_attribute($taxonomy);

        ?> 
        <div class="prodAttr">
            <p class="prodAttr__title"><?php echo $attribute_name?></p>
            <p class="prodAttr__value"><?php echo $_product->get_attribute($taxonomy) ?></p>
        </div>

        <?php
            $i++;
            if ($i == 4) break;
    }

    // Display (output)
    // echo '<div class="product-attributes"><span>'. implode( '</span> <span>', $attributes ) . '</span></div>';

}

有效。已关闭