在 WooCommerce 结账帐单街道地址字段后显示自定义按钮

问题描述 投票:0回答:1

我一直在尝试更改结帐页面中帐单详细信息表单的字段顺序。我已经在其中添加了一个名为“计算送货费”的按钮。目前它显示在所有字段之后,我需要在街道地址字段之后显示该按钮。

我已经尝试使用此代码(如下)来添加按钮,它显示在帐单详细信息表单的末尾。另外,我尝试按优先级更改顺序,但未能在街道地址字段之后显示。

// Add a button after the billing form in WooCommerce checkout
add_action('woocommerce_after_checkout_billing_form', 'add_custom_button_after_billing_form');
function add_custom_button_after_billing_form() {
    // include_once(plugin_dir_path(__FILE__) . 'distancecal.php'); // Include PHP functions file
    ?>
    <div id="custom-button-wrapper">
        <button type="button" id="custom-button" class="button alt"><?php _e('Calculate Delivery Fee'); ?></button>
    </div>
<?php
}
php wordpress woocommerce field checkout
1个回答
0
投票

您可以向 WooCommerce 表单字段添加新字段按钮(类型“按钮”),例如:

add_filter( 'woocommerce_form_field_button', 'create_button_form_field_type', 10, 4 );
function create_button_form_field_type( $field, $key, $args, $value ){
    return sprintf('<p class="form-row %s" id="%s_field" data-priority="%s">
        <button type="%s" id="%s" class="%s">%s</button>
    </p>',
    implode(' ', $args['class']), esc_attr($key), $args['priority'] ? $args['priority'] : '', 
    $args['type'], esc_attr($key), $args['input-class'], $args['label'] );
}

现在您可以在账单街道地址字段后显示自定义按钮:

add_filter( 'woocommerce_form_field_button', 'create_button_form_field_type', 10, 4 );
function create_button_form_field_type( $field, $key, $args, $value ){
    return sprintf('<p class="form-row %s" id="%s_field" data-priority="%s">
        <button type="%s" id="%s" class="%s">%s</button>
    </p>',
    implode(' ', $args['class']), esc_attr($key), $args['priority'] ? $args['priority'] : '', 
    $args['type'], esc_attr($key), $args['input-class'], $args['label'] );
}

add_action('woocommerce_checkout_fields', 'insert_custom_button_in_billing_form');
function insert_custom_button_in_billing_form( $fields ) {
    // include_once(plugin_dir_path(__FILE__) . 'distancecal.php'); // Include PHP functions file
    
    $fields['billing']['custom-button'] = array(
        'type'         => 'button',
        'label'        => __('Calculate Delivery Fee'),
        'class'        =>  array('form-row-wide'),,
        'input-class'  => 'button alt',
        'priority'     => 61, // <== Field location (after Street address fields)
    );
    return $fields;
}

按钮位置:您可以微调

'priority'
参数来更改按钮位置。

代码位于子主题的functions.php文件中(或插件中)。

你会得到类似的东西:

© www.soinside.com 2019 - 2024. All rights reserved.