php - 在单一和可变产品的“附加信息区域”上显示 SKU
问题描述
我正在尝试在单个产品附加信息选项卡的表格行中显示产品的 SKU。
我尝试使用woocommerce_display_product_attributes
过滤器并显示它(下面是我的代码示例),但它只适用于简单的产品。
When using variable products with different SKU, the field are not updated when (dropdown select) variation is selected and only show blank. 有没有合适的方法来做到这一点?
这是我当前的代码:
// Displays SKU/Part# to Single product Additional information table rows
add_filter('woocommerce_display_product_attributes', 'wc_display_sku_additional_info_table', 10, 2);
function wc_display_sku_additional_info_table( $product_attributes, $product ){
// Get product SKU
$get_sku = ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' );
$product_attributes[] = [
'label' => __('SKU', 'woocommerce'),
'value' => $get_sku,
];
return $product_attributes;
}
解决方案
这应该足够了,注释并添加到我的代码中
- 对于
single
和variable
产品,将 SKU 表行添加到附加信息选项卡中。 variable
SKU 表行会随着产品的下拉选择菜单相应更新
function display_product_attributes( $product_attributes, $product ) {
// Simple product
if ( $product->is_type('simple' ) ) {
// Get product SKU
$get_sku = ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' );
// Add
$product_attributes[ 'sku-field sku-field-single' ] = array(
'label' => __('SKU', 'woocommerce'),
'value' => $get_sku,
);
}
// Variable product
elseif ( $product->is_type('variable' ) ) {
// Get childIDs in an array
$children_ids = $product->get_children();
// Loop
foreach ( $children_ids as $child_id ) {
// Get product
$product = wc_get_product( $child_id );
// Get product SKU
$get_sku = ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' );
// Add
$product_attributes[ 'sku-field sku-field-variable sku-field-variable-' . $child_id ] = array(
'label' => __('SKU', 'woocommerce'),
'value' => $get_sku,
);
}
?>
<script>
jQuery(document).ready(function($) {
// Hide all rows
$( '.sku-field-variable' ).css( 'display', 'none' );
// Change
$( 'input.variation_id' ).change( function() {
// Hide all rows
$( '.sku-field-variable' ).css( 'display', 'none' );
if( $( 'input.variation_id' ).val() != '' ) {
var var_id = $( 'input.variation_id' ).val();
// Display current
$( '.sku-field-variable-' + var_id ).css( 'display', 'table-row' );
}
});
});
</script>
<?php
}
return $product_attributes;
}
add_filter('woocommerce_display_product_attributes', 'display_product_attributes', 10, 2);
推荐阅读
- android - 使用 Activity 在 Androidx 上进行 Koin 测试
- .htaccess - 某些 url 的 301 重定向不起作用
- sql-server - 如何通过 SQL 更新 XLSX 表?
- python - 如何在 sphinx 中使用 __doc__ 中的换行符
- laravel - 为存储在 S3 上的文件设置文件名
- java - 使用 Set 创建自定义谓词
和字符串作为参数 - javascript - window.open 导致主窗口退出全屏模式。有解决方法吗?
- react-admin - 将导出默认值添加到 DatagridBody
- wpf - WPF DataGrid 自定义模板自动生成的列内容绑定
- pagespeed-insights - 在 PageSpeed Insights 中下载优化的图像、脚本和 CSS 资源时发生了什么?