javascript - 无法使用已售罄消息禁用缺货产品变体的功能
问题描述
在我的functions.php 中,我试图在我的产品变体的下拉菜单中添加一条已售罄的消息。例如,如果我的衬衫有小号、中号和大号的款式,而大号的缺货,在下拉菜单中,用户应该会看到大号选项被禁用,并且在“大号”旁边包含一条售罄消息。其他变体应保持活动状态。
我在下面的代码中遇到的问题如下:
- 注释的代码会禁用正确的缺货产品变体,但不会添加售罄消息。
- 活动代码确实添加了售罄消息,但它禁用了所有产品变体,即使它只有一个变体缺货。
如何修复代码以执行我需要它执行的操作?
/**
* Disable out of stock variations
* https://github.com/woocommerce/woocommerce/blob/826af31e1e3b6e8e5fc3c1004cc517c5c5ec25b1/includes/class-wc-product-variation.php
* @return Boolean
*/
// function wcbv_variation_is_active( $active, $variation ) {
// if( ! $variation->is_in_stock() ) {
// return false;
// }
// return $active;
// }
// add_filter( 'woocommerce_variation_is_active', 'wcbv_variation_is_active', 10, 2 );
add_action( 'woocommerce_variation_is_active', 'woocommerce_sold_out_dropdown' );
function woocommerce_sold_out_dropdown() {
?>
<script type="text/javascript">
jQuery( document ).bind( 'woocommerce_update_variation_values', function() {
jQuery( '.variations select option' ).each( function( index, el ) {
var sold_out = '<?php _e( 'sold out', 'woocommerce' ); ?>';
var re = new RegExp( ' - ' + sold_out + '$' );
el = jQuery( el );
if ( el.is( ':disabled' ) ) {
if ( ! el.html().match( re ) ) el.html( el.html() + ' - ' + sold_out );
} else {
if ( el.html().match( re ) ) el.html( el.html().replace( re,'' ) );
}
} );
} );
</script>
<?php
}
解决方案
您可以使用此代码(您的代码)获得所需的内容:
// disable options for unavailable variants
add_filter( 'woocommerce_variation_is_active', 'wcbv_variation_is_active', 10, 2 );
function wcbv_variation_is_active( $active, $variation ) {
if ( ! $variation->is_in_stock() ) {
return false;
}
return $active;
}
现在,要根据股票状态更改每个选项的名称,您可以woocommerce_variation_option_name
像这样使用钩子:
add_filter( 'woocommerce_variation_option_name','add_stock_status_after_option_name', 10, 1 );
function add_stock_status_after_option_name( $option ) {
// only in frontend
if ( is_admin() ) {
return $option;
}
// get variable product object
global $product;
$variation_ids = $product->get_children();
foreach ( $variation_ids as $variation_id ) {
$variation = wc_get_product( $variation_id );
$variation_attributes = $variation->get_variation_attributes();
foreach ( $variation_attributes as $key => $value ) {
// slugify option name
$option_slug = sanitize_title( $option );
// check if the current option is equal to the variation slug
if ( $value == $option_slug ) {
// check if it is out of stock
if ( ! $variation->is_in_stock() ) {
return $option . ' (Out of stock)';
}
}
}
}
return $option;
}
该代码已经过测试并且可以正常工作。它需要添加到您的主题的functions.php。
推荐阅读
- sql - 如何在不使用 COUNT(*) 的情况下获取 SQL 临时表中的行数
- php - 为什么 HTTP 请求在 Tinker 中可以正常工作,但在 Laravel 7 的应用程序中却不行?
- python - 'pip3 install patool' 后无法使用 patoolib
- python - 如何有条件地从列表中删除项目
- php - 我正在尝试使用教义和查询生成器在 symfony 中创建列表过滤器
- firebase - 如何从 ERP 系统登录 Firebase?
- java - 缺少依赖版本 - io.vertx:vertx-stack-depchain:jar 的“dependencies.dependency.version”缺失
- android - 在 Android 中更快地对 DocumentFiles 数组进行排序
- python - 句子中单词之间的关系
- wpf - WPF。GeometryDrawing 的画笔总是只有透明的