【发布时间】:2016-02-16 17:07:06
【问题描述】:
我正在尝试在 woocommerce 中自定义本地取货配送选项。基本上,如果从 woocommerce 设置中选择了本地取货选项,它将显示在每个产品的结帐时。我想对其进行自定义,使其仅显示在选定的产品中。
所以我在产品编辑页面上添加了一个新的复选框自定义字段元。如果产品上提供本地取货,则应选中复选框,如果本地取货不可用,则取消选中复选框。
functions.php 中的代码如下所示:
<?php
// Display Fields
add_action( 'woocommerce_product_options_shipping', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Checkbox Local Pickup / Collection Available
woocommerce_wp_checkbox(
array(
'id' => '_shipping_collection',
'wrapper_class' => 'show_if_simple',
'label' => __('Local Pickup / Collection Available', 'woocommerce' ),
'description' => __( 'This product is available for collection', 'woocommerce' )
)
);
echo '</div>';
}
function woo_add_custom_general_fields_save( $post_id ){
// Checkbox Local Pickup / Collection Available - Save Data
$collection_checkbox = isset( $_POST['_shipping_collection'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_shipping_collection', $collection_checkbox );
}
?>
到目前为止一切正常,复选框正在显示和保存。
正如我之前提到的,本地取货选项适用于每件产品。我想对其进行自定义,使其仅显示在此复选框(_shipping_collection)为checked的产品上
结帐时显示的本地取货元素在此处生成: https://github.com/woothemes/woocommerce/blob/master/templates/cart/cart-shipping.php
使用以下代码:
<ul id="shipping_method">
<?php foreach ( $available_methods as $method ) : ?>
<li>
<input type="radio" name="shipping_method[<?php echo $index; ?>]" data-index="<?php echo $index; ?>" id="shipping_method_<?php echo $index; ?>_<?php echo sanitize_title( $method->id ); ?>" value="<?php echo esc_attr( $method->id ); ?>" <?php checked( $method->id, $chosen_method ); ?> class="shipping_method" />
<label for="shipping_method_<?php echo $index; ?>_<?php echo sanitize_title( $method->id ); ?>" id="shipping_method_<?php echo $index; ?>_<?php echo sanitize_title( $method->id ); ?>"><?php echo wp_kses_post( wc_cart_totals_shipping_method_label( $method ) ); ?></label>
</li>
<?php endforeach; ?>
</ul>
我在标签中添加了 ID 选择器,因此在隐藏标签时可以通过其 ID 识别标签。
在前端结账时,代码会生成如下ID:
#shipping_method_0_local_pickup
所以如果我现在尝试使用 CSS 隐藏它:
#shipping_method_0_local_pickup {
display: none;
}
效果很好!结帐时隐藏了该字段。
所以我现在认为我应该使用 Jquery 来实现复选框功能,经过一番搜索后,我挖掘了一个示例脚本,因此在更改其中的选择器以适合我的选择器后,我最终得到了这个:
$('#_shipping_collection').click(function() {
if($(this).is(":checked")) {
$('#shipping_method_0_local_pickup').show();
} else {
$('#shipping_method_0_local_pickup').hide();
}
})
我想我应该把这个脚本放在这个文件里: https://github.com/woothemes/woocommerce/blob/master/assets/js/frontend/add-payment-method.js
但不幸的是,这似乎不起作用。
您有什么建议吗?
【问题讨论】:
标签: javascript php jquery wordpress woocommerce