编程语言
首页 > 编程语言> > php-在WooCommerce结帐表单中显示自定义表值

php-在WooCommerce结帐表单中显示自定义表值

作者:互联网

我想在WooCommerce签出公司名称字段中显示外部表值.我们可以创建外部表并插入一些公司名称.

当用户在结帐字段中注册我们的服务时,客户应在自定义选择选项字段中选择公司名称.此值应从自定义数据库表中显示.

enter image description here

我该如何实现?

提前致谢.

解决方法:

我们将首先取消设置公司的字段类型,然后将其更改为类型“选择”(选择器).然后,我们将对查询进行查询,以从您的自定义数据库表中获取所有选项键/值(比方说被称为“ wp_companies”):

(仅用于测试)此处没有数据库查询(公司有3个选项):

add_filter( 'woocommerce_default_address_fields' , 'set_custom_company_checkout_field' );
function set_custom_company_checkout_field( $address_fields ) {

    unset($fields['company']['type']);

    $address_fields['company']['type'] = 'select';
    $address_fields['company']['options'] = array(
        'option_1' => 'Company 1',
        'option_2' => 'Company 2',
        'option_3' => 'Company 3'
    );
    // (optional) 
    // $address_fields['company']['default'] = 'Company 1';

    return $address_fields;
}

将此代码粘贴到活动子主题(或主题)中的function.php文件中.

此代码已经过测试,可以正常工作……

THE REAL CODE: Making the query from database custom table (to be adapted):

add_filter( 'woocommerce_default_address_fields' , 'set_custom_company_checkout_field' );
function set_custom_company_checkout_field( $address_fields ) {

    // Unset company field type
    unset($fields['company']['type']);

    global $wpdb;
    $select_options = array();

    // @@@ you will need to replace names table and columns and adapt this !!!
    $query = "SELECT id, company FROM table";
    $companies_name  = $wpdb->get_results($query);

    // Storing object $company_name keys/values in $select_options array
    foreach ( $companies_name as $company_name ) 
    {
        $key = 'option_'. $company_name->ID;
        $value = $company_name->custom_column_value;
        $select_options[$key] = $value ;
    }

    $address_fields['company']['type'] = 'select';
    $address_fields['company']['options'] = $select_options;
    // (optional) 
    // $address_fields['company']['default'] = $select_options['option_1'];

    return $address_fields;
} 

将此代码粘贴到活动子主题(或主题)中的function.php文件中.

参考文献:

> WooThemes – Customizing checkout fields using actions and filters
> WooCommerce – Overriding billing state and post code on existing checkout fields

标签:custom-fields,woocommerce,wordpress,mysql,php
来源: https://codeday.me/bug/20191118/2027843.html