php - 带有链接的 Woocommerce 产品变体
问题描述
在该类别中,我试图通过每个变体的链接来显示其下方每个产品的变体。
目前我有所有的文本输出,但无法理解如何获取链接。我不擅长 PHP,如果我真的很愚蠢,我很抱歉。
以下是我目前所掌握的内容,这些内容是根据我在周围找到并调整的一些建议拼凑而成的。
先感谢您。
if($product->is_type('变量')){ foreach($product->get_available_variations() as $variation){ $属性 = 数组(); foreach($variation['attributes'] as $key => $value){ $taxonomy = str_replace('attribute_', '', $key ); $taxonomy_label = get_taxonomy( $taxonomy )->labels->singular_name; $term_name = get_term_by('slug', $value, $taxonomy)->name; $attributes[] = $term_name; } 回声' '.implode('|', $attributes ).''; $active_price = floatval($variation['display_price']); // 有效价格 $regular_price = floatval($variation['display_regular_price']); // 正常价格 if( $active_price != $regular_price ){ $sale_price = $active_price; // 销售价格 } 回声' '.$variation['price_html'].'
'; } };
解决方案
您可以get_permalink()
通过为其提供变体 ID 来使用该函数来检索变体的永久链接。
属性保存在 中,$variation
因此您可以简单地使用implode( ' | ', $variation['attributes'] )
. 无需再次检索它们。
此外,您检查销售价格与正常价格的部分似乎并没有做很多事情,因为您$variation['price_html']
最终选择了。如果您只是想显示当前(销售)价格,我会$variation['display_price']
结合使用该wc_price()
函数来获取正确的价格格式。
最后,您可以更好地使用printf()
创建格式化输出,而不是一个接一个地回显每个变量。
总的来说,您的代码应如下所示:
if ( $product->is_type('variable') ) {
foreach ( $product->get_available_variations() as $variation ) {
printf( '<a href="%s"><p class="variation">%s %s</p></a>', get_permalink( $variation['variation_id'] ), implode( ' | ', $variation['attributes'] ), wc_price( $variation['display_price'] ) );
}
}
推荐阅读
- javascript - 如何使用 javascript 正确发布 x-www-form-urlencoded 数据?
- blockchain - 需要从任何区块链上的块中检索交易
- sql-server - 如何在 MSSQL 中查找两个表之间的差异
- json - Webscraper,将列表提取到.json?
- android - 从 Kotlin Generic 获取泛型类
- linux - 如何从多个文件中打印每第 n 行并将其写入第 n 行的每一组?
- email - 安装postfixadmin?
- api - 无法使用 Google Tag Manager API 在 Google Tag Manager 中创建标签
- javascript - 从 AJAX 获取原始 HTTP 响应
- linux - Nginx - Lua 无法保存图像文件