wordpress - 通过可变产品 ID,如何按指定的 SKU 显示变体产品
问题描述
我想按指定的 skus 显示一些变体产品,而不是在可变产品 ID 中显示所有变体产品。
例如: 变量产品 id 是:#556
- 可变产品 id #556 的子变体产品,我希望它按指定的 sku 在索引页面上显示变体产品,以显示图像、标题和指向可变产品 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>';
}
?>
如果你能帮忙,请。尝试了很长时间,似乎没有任何效果。
先感谢您。
解决方案
您可以通过初始化一系列您不想看到的产品变体 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>';
}
该代码无法测试,但它应该可以工作。
推荐阅读
- vue.js - 如何在 vue 文件中使用“paper.on('cell:pointerdblclick', function (cellView){})”之类的方法?
- javascript - Black border arround content in Electron
- rest - 我应该在 OpenAPI 中定义不同的 POST 和 PATCH 模型吗?
- javascript - 将 html 页面加载到 html 页面中会禁用滚动条
- r - 计算并附加列中相等字符串的日期差异
- r - 在 Ubuntu 18.04 上编译 R 3.6.1 时出错
- c# - Selenium 网格在浏览器之间混合测试
- python - python - 用 001,002 等重命名文件
- php - Html2Canvas 通过 php 将 png 图像保存到服务器,显示一半图像并且文件大小减小
- jenkins - 詹金斯管道脚本处理子目录中的模块