首页 > 解决方案 > 通过可变产品 ID,如何按指定的 SKU 显示变体产品

问题描述

我想按指定的 skus 显示一些变体产品,而不是在可变产品 ID 中显示所有变体产品。

例如: 变量产品 id 是:#556

我下面的代码正在运行,但它显示了可变产品 id 556 中产品的每一个变体。我需要选择通过其指定的 skus 显示的变体产品以显示图像、标题和链接。

这是我的代码:

<?php 
$product = new WC_Product_Variable( '556' ); 
$variations = $product->get_available_variations(); 

foreach ( $product->get_variation_attributes() as $attribute_name => $attribute ) { 
    $attributes[] = array( 'term_name' => ucwords( str_replace( 'attribute_', '', 
    wc_attribute_taxonomy_slug( $attribute_name ) ) ), 'option' => $attribute, ); 
} 

foreach ( $variations as $variation ) { 
    echo '<div class="index_main_products col-xs-12 col-sm-12 col-md-6 col-lg-4 col-xl-3">';
    echo '<a href="'.$product->get_permalink().'#variations-table">';
    echo "<img src=" . $variation['image']['thumb_src'] .">";
    echo '</a>';

    echo '<h2>';
    echo implode(str_replace('_', ' ',  $variation['attributes']));
    echo '</h2>';

    echo '<a class="index_button button" href="'.$product->get_permalink().'">View Product</a>';
    echo '</div>';
}
?>

如果你能帮忙,请。尝试了很长时间,似乎没有任何效果。

先感谢您。

标签: wordpresswoocommerceproduct-variationsvariable-product

解决方案


您可以通过初始化一系列您不想看到的产品变体 sku 来做到这一点。

然后在循环中,您可以检查当前变体 sku 是否存在于数组中。如果是,请不要显示它并继续下一个产品。

$product = new WC_Product_Variable( 556 );
// initializes an array with product variation skus not to be displayed
$skus = array( 'sku-1', 'sku-2', 'sku-3' );
$variations = $product->get_available_variations(); 

foreach ( $product->get_variation_attributes() as $attribute_name => $attribute ) { 
    $attributes[] = array( 'term_name' => ucwords( str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $attribute_name ) ) ), 'option' => $attribute, ); 
} 

foreach ( $variations as $variation ) { 
    // if the sku of the product variation is not in the array it continues to the next variation
    if ( ! in_array( $variation['sku'], $skus ) ) {
        continue;
    }
    // otherwise
    echo '<div class="index_main_products col-xs-12 col-sm-12 col-md-6 col-lg-4 col-xl-3">';
    echo '<a href="'.$product->get_permalink().'#variations-table">';
    echo "<img src=" . $variation['image']['thumb_src'] .">";
    echo '</a>';
    echo '<h2>';
    echo implode(str_replace('_', ' ',  $variation['attributes']));
    echo '</h2>';
    echo '<a class="index_button button" href="'.$product->get_permalink().'">View Product</a>';
    echo '</div>';
}

该代码无法测试,但它应该可以工作。


推荐阅读