php 如何在WooCommerce计费数据中显示新字段的数据?

cmssoen2  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(101)

bounty还有5天到期。回答此问题可获得+300声望奖励。gemita想要奖励现有答案:我想奖励一个答案,你已经给了它的简单和有效的功能

如何在WooCommerce计费数据中显示新字段的数据?
我已经在页面上创建了“我的帐户”的WooCommerce,在账单地址,两个新字段。这些仅对某些用户角色(“管理员”)可见,
字段显示在checkout in this screenshot
1 -带有文本标签的复选框:'label' => __('I have Surcharge'(这是我需要在电子邮件中显示的)
此字段是使用以下代码创建的,并且

add_filter( 'woocommerce_billing_fields', 'custom_checkbox_below_billing_company' );

function custom_checkbox_below_billing_company( $fields ) {
    //Show the checkbox only to users with the role "administratorr"
    if ( user_can( wp_get_current_user(), 'administrator' ) ) {
        $fields['billing_custom_checkbox'] = array(
            'type'          => 'checkbox',
            'label'         => __('Tengo Recargo', 'woocommerce'),
            'class'         => array('form-row-wide'),
            'priority'      => 30,
            'required'      => false,
            'clear'         => true,
            'default'       => 0,
        );
    }
    return $fields;
}

// Save the value of the checkbox in the database
add_action( 'woocommerce_customer_save_address', 'save_billing_custom_checkbox', 10, 2 );

function save_billing_custom_checkbox( $customer_id, $load_address ) {
    if ( isset( $_POST['billing_custom_checkbox'] ) ) {
        $checkbox_value = sanitize_text_field( $_POST['billing_custom_checkbox'] );
        update_user_meta( $customer_id, 'billing_custom_checkbox', $checkbox_value );
    } else {
        update_user_meta( $customer_id, 'billing_custom_checkbox', '0' );
    }
}

/* SENDING THE FIELD IN THE POST*/

// Show checkbox label in billing address
add_action( 'woocommerce_admin_billing_fields', 'show_billing_custom_checkbox_label' );
add_action( 'woocommerce_billing_fields', 'show_billing_custom_checkbox_label' );

function show_billing_custom_checkbox_label( $fields ) {
    if ( isset( $fields['billing_custom_checkbox'] ) ) {
        $fields['billing_custom_checkbox']['label'] .= ' ' . __('(Tengo Recargo de Ekivalencia)', 'woocommerce');
    }
    return $fields;
}

add_filter( 'woocommerce_email_customer_details_fields', 'add_custom_checkbox_to_emails', 10, 3 );

function add_custom_checkbox_to_emails( $fields, $sent_to_admin, $order ) {
    $checkbox_value = get_user_meta( $order->get_user_id(), 'billing_custom_checkbox', true ); // Get the value of the checkbox
    $fields['billing_custom_checkbox'] = array(
        'label' => __('Tengo Recargo de Ekivalencia', 'woocommerce') . ' ' . ($checkbox_value ? 'SI' : 'NO'), //Add the value of the checkbox in the label
        'value' => $checkbox_value ? 'SI' : 'NO', // Agrega el valor del checkbox en el valor
    );
    return $fields;
}

2 -用于输入公司税务识别号的字段,NIF/CIF:'label' => __('NIF/CIF', 'woocommerce'),
NIF/CIF字段已按如下方式创建,但在发送给客户端和管理员的电子邮件中显示它的方式失败了

add_filter('woocommerce_checkout_fields', 'add_custom_billing_field');
function add_custom_billing_field($fields)
{
  // Get the role of the current user
  $user = get_userdata( get_current_user_id() );
  if ( ! empty( $user ) && in_array( 'administrator', (array) $user->roles ) ) {

    $current_user = wp_get_current_user();
    $saved_license_no = $current_user->license_no;

    // Add the NIF/CIF field to the billing address editing form
    $fields['billing_license_no'] = array(
      'label'       => __('NIF/CIF', 'woocommerce'),
      'placeholder' => __('B12345678', 'woocommerce'),
      'required'    => true,
      'clear'       => false,
      'type'        => 'text',
      'default'     => $saved_license_no,
      'class'       => array('form-row-wide'),
      'priority'    => 25, 
    );
  }

  //Return the updated array of billing fields
  return $fields;
}

/* save the new field and show it in email, checkout, etc... */
add_action('woocommerce_checkout_update_order_meta', 'bbloomer_save_new_checkout_field');
function bbloomer_save_new_checkout_field($order_id)
{
  if (isset($_POST['billing_license_no'])) { //Check if field value was sent
    update_post_meta($order_id, '_license_no', wc_clean($_POST['billing_license_no'])); //Clear value before saving
  }
}

add_action('woocommerce_thankyou', 'bbloomer_show_new_checkout_field_thankyou');
function bbloomer_show_new_checkout_field_thankyou($order_id)
{
  if (get_post_meta($order_id, '_license_no', true)) echo '<p><strong>NIF/CIF:</strong> ' . get_post_meta($order_id, '_license_no', true) . '</p>';
}

add_filter('woocommerce_order_details_after_order_table', 'bbloomer_show_new_checkout_field_order', 20, 1);
add_action('woocommerce_admin_order_data_after_billing_address', 'bbloomer_show_new_checkout_field_order');
function bbloomer_show_new_checkout_field_order($order)
{
  $order_id = $order->get_id();
  if (get_post_meta($order_id, '_license_no', true)) echo '<p><strong>NIF/CIF:</strong> ' . get_post_meta($order_id, '_license_no', true) . '</p>';
}

add_action('woocommerce_email_after_order_table', 'bbloomer_show_new_checkout_field_emails', 20, 4);

function bbloomer_show_new_checkout_field_emails($order, $sent_to_admin, $plain_text, $email)
{
  if (get_post_meta($order->get_id(), '_license_no', true)) echo '<p><strong>NIF/CIF:</strong> ' . get_post_meta($order->get_id(), '_license_no', true) . '</p>';
}

这些字段是从用户的帐户页面my-account/edit-address/billing/编辑的,并且在下订单时也会显示在Checkout中。
我只需要这些数据是WooCommerce计费数据的一部分,并与其余数据沿着发送:姓名、公司名称、地址等
可以在屏幕截图上看到。/// admin-Mail
现在它们在邮件中发送,但在地址范围之外,如您所见in the screenshot (administrator-Mail.png)
但这些数据不是WooCommerce结构的一部分,因此在生成发票(invoice screenshot - bill.jpg)时不会显示
我应该怎么做,使这些数据是WooCommerce账单地址的一部分?
也许它可以通过编辑WooCommerce结构来实现,但我不知道这是否可能,如果可以做到,它将如何完成?
如何才能以最安全的方式做到这一点?

e7arh2l6

e7arh2l61#

<?php
/**
 * Add custom WooCommerce checkout fields for administrator users.
 *
 * @param   array   $fields The existing billing fields.
 * @return  array   $fields The updated billing fields.
 */
function custom_woocommerce_checkout_fields( $fields ) {

    // Get the current user
    $current_user = wp_get_current_user();

    // Check if the current user is an administrator
    if ( in_array( 'administrator', (array) $current_user->roles ) ) {

        // Get the saved license number for the current user
        $saved_license_no = $current_user->license_no;

        // Add the custom fields to the billing fields array
        $fields['billing_licenseno'] = array(
            'label'       => __( 'NIF/CIF', 'woocommerce' ),
            'placeholder' => __( 'B12345678', 'woocommerce' ),
            'type'        => 'text',
            'required'    => true,
            'clear'       => false,
            'default'     => $saved_license_no,
            'class'       => array( 'form-row-wide' ),
            'priority'    => 25,
        );

        $fields['billing_customcheckbox'] = array(
            'label'         => __('Tengo Recargo (Tengo Recargo de Ekivalencia)', 'woocommerce'),
            'type'          => 'checkbox',
            'required'      => false,
            'clear'         => true,
            'default'       => 0,
            'class'         => array('form-row-wide'),
            'priority'      => 30,
        );
    }
    
    return $fields;
}
add_filter('woocommerce_billing_fields', 'custom_woocommerce_checkout_fields');

/**
 * Filters the WooCommerce order formatted billing address.
 * @param   array   $address The array of address.
 * @param   object  $order The order object.
 * @return  array   The updated array of address.
 */
function add_custom_woocommerce_order_fields( $address, $order ) {
    // Get the license number from the order meta.
    $address['licenseno'] = $order->get_meta( '_billing_licenseno' );

    // Get the custom checkbox value from the order meta.
    $address['customcheckbox'] = $order->get_meta( '_billing_customcheckbox' ) ? __( 'SI', 'text-domain' ) : __( 'NO', 'text-domain' );

    return $address;
}
add_filter( 'woocommerce_order_formatted_billing_address', 'add_custom_woocommerce_order_fields', 10, 2 );

/**
 * Saves the billing custom checkbox value on customer save address.
 * @param   int     $customer_id The customer ID.
 * @param   string  $load_address The address type.
 * @return  void
 */
function save_billing_custom_checkbox( $customer_id, $load_address ) {
    if ( isset( $_POST['billing_customcheckbox'] ) ) {
        // Sanitize the custom checkbox value.
        $checkbox_value = sanitize_text_field( wp_unslash( $_POST['billing_customcheckbox'] ) );

        // Update the user meta with the custom checkbox value.
        update_user_meta( $customer_id, 'billing_customcheckbox', $checkbox_value );
    } else {
        // If the custom checkbox value is not set, update the user meta with 0.
        update_user_meta( $customer_id, 'billing_customcheckbox', '0' );
    }
}
add_action( 'woocommerce_customer_save_address', 'save_billing_custom_checkbox', 10, 2 );

/**
 * Filters the WooCommerce localisation address formats.
 * @param   array   $address_formats The array of address formats.
 * @return  array   The updated array of address formats.
 */
function custom_localisation_address_formats( $address_formats ) {
    
    foreach ( $address_formats as $country_code => $address_format ) {
        $address_formats[ $country_code ] = str_replace(
            "{name}",
            "{name}\n{licenseno}\n{customcheckbox}",
            $address_formats[ $country_code ]
        );
    }
    
    return $address_formats;
}
add_filter( 'woocommerce_localisation_address_formats', 'custom_localisation_address_formats', 50, 1 );

/**
 * Filters the WooCommerce formatted address replacements.
 * @param   array   $replacements The array of address replacements.
 * @param   array   $args The array of arguments.
 * @return  array   The updated array of address replacements.
 */
function formatted_address_custom_replacements( $replacements, $args ) {
    $replacements['{licenseno}'] = ! empty( $args['licenseno'] ) ? $args['licenseno'] : '';
    $replacements['{customcheckbox}'] = ! empty( $args['customcheckbox'] ) ? $args['customcheckbox'] : '';

    return $replacements;
}
add_filter( 'woocommerce_formatted_address_replacements', 'formatted_address_custom_replacements', 10, 2 );

测试它,让我知道任何变化或如果错误occure

nukf8bse

nukf8bse2#

要在WooCommerce账单数据中显示新字段的数据,您需要添加自定义代码:
1.将新字段添加到帐单表单
1.将新字段数据保存到订单 meta数据中
1.在订单详细信息页面、电子邮件和其他相关位置显示新字段数据
下面是一个示例代码片段,演示了如何将公司名称的新字段添加到WooCommerce账单表单并将数据保存到订单 meta:

// Step 1: Add new field to billing form
add_filter( 'woocommerce_billing_fields', 'add_company_name_field' );

function add_company_name_field( $fields ) {
    $fields['billing_company_name'] = array(
        'label'       => __( 'Company Name', 'woocommerce' ),
        'required'    => false,
        'class'       => array( 'form-row-wide' ),
        'clear'       => true,
        'priority'    => 25,
    );

    return $fields;
}

// Step 2: Save new field data to order meta
add_action( 'woocommerce_checkout_create_order', 'save_company_name_field' );

function save_company_name_field( $order ) {
    if ( ! empty( $_POST['billing_company_name'] ) ) {
        $order->update_meta_data( '_billing_company_name', sanitize_text_field( $_POST['billing_company_name'] ) );
    }
}

// Step 3: Display new field data in relevant places
add_filter( 'woocommerce_order_formatted_billing_address', 'display_company_name_in_billing_address', 10, 2 );

function display_company_name_in_billing_address( $address, $order ) {
    $company_name = $order->get_meta( '_billing_company_name', true );

    if ( $company_name ) {
        $address .= "\n" . $company_name;
    }

    return $address;
}

在这个示例代码中,我们使用woocommerce_billing_fields过滤器将“公司名称”的新字段添加到账单表单。然后,我们使用woocommerce_checkout_create_order操作将该字段中的数据保存到订单 meta数据中。
最后,我们使用woocommerce_order_formatted_billing_address过滤器在订单详情页面和电子邮件的账单地址部分显示公司名称
您可以根据需要自定义字段名称、标签和 meta密钥。此外,您可能需要更新使用计费数据的其他函数,以包括新的字段数据。

相关问题