php WooCommerce自定义创建帐户复选框在结帐

qnzebej0  于 2023-02-28  发布在  PHP
关注(0)|答案(1)|浏览(136)

bounty将于明天到期。回答此问题可获得+50的声誉奖励。Nik7正在寻找来自声誉良好来源的答案

我们刚刚将结帐页面上的WooCommerce帐户密码字段从“帐户”组移动并合并到“账单”字段组。这很好用。此外,我们创建了一个新的复选框字段并将其添加到账单部分。没有它,“创建帐户”复选框仍将在默认位置。为此,我们使用jQuery创建了一个新的复选框。
感谢以下文章:

使用我们当前的代码,移动的密码字段总是可见的。我们希望它与WooCommerce默认工作方式相同。这意味着密码字段应该只在复选框激活时可见。WooCommerce默认有一个很好的隐藏和显示CSS。但是,我不能使用相同的CSS(或者脚本?!)。
我们如何将自定义复选框与帐户密码字段联系起来?

// Move Account password field into billing section
function move_password_field($checkout_fields){
    // Move Account Password into Billing
    $checkout_fields['billing']['account_password'] = $checkout_fields['account']['account_password']; 

    // Remove Password from Billing
    unset($checkout_fields['account']['account_password']);

    return $checkout_fields;
}

add_filter('woocommerce_checkout_fields', 'move_password_field', 999); 

// CSS rules
add_action( 'woocommerce_before_checkout_billing_form', 'move_checkout_create_an_account_css' );
function move_checkout_create_an_account_css() {
    if( ! is_user_logged_in() ) :
    ?><style>
        .woocommerce-account-fields label.woocommerce-form__label-for-checkbox {display: none !important;}
        #account_cb_field {margin-top: 32px;}
        #account_cb_field input {margin-right: 6px;}
    </style>
    <?php
    endif;
}

// Add a checkbox to billing section
add_filter( 'woocommerce_checkout_fields', 'move_checkout_create_an_account_checkbox' );
function move_checkout_create_an_account_checkbox( $fields ) {
    if( ! is_user_logged_in() ) {
        // Make email field on half on left side
        $fields['billing']['billing_email']['class'] = array('form-row-wide');

        // Custom checkbox on half right side
        $fields['billing']['account_cb'] = array(
            'type'  => 'checkbox',
            'label' => __("Create an account?", "woocommerce"),
            'class' => array('form-row-wide'),
        );
    }
    return $fields;
}

// remove "(optional)" from the new checkbox
add_filter( 'woocommerce_form_field' , 'remove_checkout_optional_fields_label', 10, 4 );
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() && $key === 'account_cb' ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

// The jQuery code
add_action( 'wp_footer', 'move_checkout_create_an_account_js' );
function move_checkout_create_an_account_js() {
    if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) :
    ?><script>
    (function($){
        $('input[name=account_cb]').on( 'click', function() {
            $('input[name=createaccount]').trigger('click');
        });
    })(jQuery);
    </script>
    <?php
    endif;
}
gmxoilav

gmxoilav1#

该代码存在一些问题,即Warning: Undefined array key "account_password" in /var/www/html/wp-content/themes/storefront/functions.php
但这是你最初问题的解决方案

// The jQuery code
add_action( 'wp_footer', 'move_checkout_create_an_account_js' );
function move_checkout_create_an_account_js() {
    if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) :
        ?>
    <script>
    (function($) {
        // re-usable function to play around with the checkout fields if needed in the
        // future
        const toggleElmVisibility = (selector = '', show = true, duration = 200) => {
            if (show) {
                $(selector).show(duration);
                return;
            }
            $(selector).hide(duration);
        }

        // hide password fields on page load, unless they have alredy checked the checkbox
        toggleElmVisibility('#account_password_field', $('#account_cb').is(':checked'));

        $('#account_cb').on('change', function() {
            toggleElmVisibility('#account_password_field', $(this).is(':checked'));
        });


        $('input[name=account_cb]').on('click', function() {
            $('input[name=createaccount]').trigger('click');
        });
    })(jQuery);
    </script>
        <?php
    endif;
}
    • 编辑:**

更改功能以添加密码字段

// Move Account password field into billing section
function move_password_field( $checkout_fields ) {
    //bail if not logged in
    if ( is_user_logged_in() ) {
        return $checkout_fields;
    }
    // Move Account Password into Billing if not logged in
    $checkout_fields['billing']['account_password'] = $checkout_fields['account']['account_password'];
    $checkout_fields['billing']['account_password'] = array(
        'label'       => __( 'Password', 'woocommerce' ), // Add custom field label
        'placeholder' => _x( 'Password', 'placeholder', 'woocommerce' ), // Add custom field placeholder
        'clear'       => false, // add clear or not
        'type'        => 'text', // add field type
    );
    unset( $checkout_fields['account']['account_password'] );
    return $checkout_fields;
} add_filter( 'woocommerce_checkout_fields', 'move_password_field', 999 );

更改remove可选文本函数以捕获新字段

// remove "(optional)" from the new checkbox
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() && ( $key === 'account_cb' || 'account_password' === $key ) ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field    = str_replace( $optional, '', $field );
    }
    return $field;
} add_filter( 'woocommerce_form_field', 'remove_checkout_optional_fields_label', 10, 4 );

提交验证

/**
 * Validate the password field if checkbox is checked on checkout submit
 *
 * @return void
 * @see https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
 */
function woocomerce_validate_pass(): void {
    if ( isset( $_POST['account_cb'] ) && empty( $_POST['account_password'] ) ) {
        wc_add_notice( __( 'Please enter a password.', 'woocommerce' ), 'error' );
    }
} add_action( 'woocommerce_after_checkout_validation', 'woocomerce_validate_pass' );

并更改为JS以拾取该字段是必需的

(function($) {
        // re-usable function to play around with the checkout fields if needed in the
        const toggleElmVisibility = (selector = '', show = true, duration = 200) => {
            if (show) {
                $(selector).show(duration, () => {
                    $(selector).addClass("validate-required");
                });
            } else {
                $(selector).hide(duration, () => {
                    $(selector).removeClass("validate-required");
                });
            }
            $(selector).removeClass("woocommerce-validated");
            $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
        }

        // hide password fields on page load, unless they have alredy checked the checkbox
        toggleElmVisibility('#account_password_field', $('#account_cb').is(':checked'));

        $('#account_cb').on('change', function() {
            toggleElmVisibility('#account_password_field', $(this).is(':checked'));
        });

        $('input[name=account_cb]').on('click', function() {
            $('input[name=createaccount]').trigger('click');
        });
    })(jQuery);

其他功能已删除,完整代码:

// Move Account password field into billing section
function move_password_field( $checkout_fields ) {
    //bail if not logged in
    if ( is_user_logged_in() ) {
        return $checkout_fields;
    }
    // Move Account Password into Billing if not logged in
    $checkout_fields['billing']['account_password'] = $checkout_fields['account']['account_password'];
    $checkout_fields['billing']['account_password'] = array(
        'label'       => __( 'Password', 'woocommerce' ), // Add custom field label
        'placeholder' => _x( 'Password', 'placeholder', 'woocommerce' ), // Add custom field placeholder
        'clear'       => false, // add clear or not
        'type'        => 'text', // add field type
    );
    unset( $checkout_fields['account']['account_password'] );
    return $checkout_fields;
} add_filter( 'woocommerce_checkout_fields', 'move_password_field', 999 );

// Add a checkbox to billing section
function move_checkout_create_an_account_checkbox( $fields ) {
    if ( is_user_logged_in() ) {
        return $fields;
    }
    // Make email field on half on left side
    $fields['billing']['billing_email']['class'] = array( 'form-row-wide' );
    // Custom checkbox on half right side
    $fields['billing']['account_cb'] = array(
        'type'        => 'checkbox',
        'label'       => __( 'Create an account?', 'woocommerce' ),
        'placeholder' => _x( 'Create an account?', 'placeholder', 'woocommerce' ),
        'class'       => array( 'form-row-wide' ),
    );
    return $fields;
} add_filter( 'woocommerce_checkout_fields', 'move_checkout_create_an_account_checkbox' );

// remove "(optional)" from the new checkbox
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() && ( $key === 'account_cb' || 'account_password' === $key ) ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field    = str_replace( $optional, '', $field );
    }
    return $field;
} add_filter( 'woocommerce_form_field', 'remove_checkout_optional_fields_label', 10, 4 );

/**
 * Validate the password field if checkbox is checked on checkout submit
 *
 * @return void
 * @see https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
 */
function woocomerce_validate_pass($fields, $errors): void {
    if ( isset( $_POST['account_cb'] ) && empty( $_POST['account_password'] ) ) {
$errors->add( 'validation', 'Please enter a password.');
    //  wc_add_notice( __( 'Please enter a password.', 'woocommerce' ), 'error' );
    }
} add_action( 'woocommerce_after_checkout_validation', 'woocomerce_validate_pass', 10, 2 );

// The jQuery code
add_action( 'wp_footer', 'move_checkout_create_an_account_js' );
function move_checkout_create_an_account_js() {
    if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) :
        ?>
    <script>
    (function($) {
        // re-usable function to play around with the checkout fields if needed in the
        const toggleElmVisibility = (selector = '', show = true, duration = 200) => {
            if (show) {
                $(selector).show(duration, () => {
                    $(selector).addClass("validate-required");
                });
            } else {
                $(selector).hide(duration, () => {
                    $(selector).removeClass("validate-required");
                });
            }
            $(selector).removeClass("woocommerce-validated");
            $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
        }

        // hide password fields on page load, unless they have alredy checked the checkbox
        toggleElmVisibility('#account_password_field', $('#account_cb').is(':checked'));

        $('#account_cb').on('change', function() {
            toggleElmVisibility('#account_password_field', $(this).is(':checked'));
        });

        $('input[name=account_cb]').on('click', function() {
            $('input[name=createaccount]').trigger('click');
        });
    })(jQuery);
    </script>
        <?php
    endif;
}

相关问题