Search code examples
wordpresswoocommercedropdownhook-woocommercewoocommerce-theming

Woocommerce how to create and populate a custom drop-down from database on the checkout page


I added new section with name donate_section before shipping form in checkout page and in it I added Select Drop-down name _done_select.

I need to populate it from database.

I'm using below query but still not able to fetch data from database function:

donate_section_donate_dropdown( $fields ) {
    
    global $wpdb;
    $ngos = $wpdb->get_results("SELECT * FROM wp_wc_temp_ngo");
    
    $output = array();
    
    $output[0] = "-----------------------";
    
    foreach( $ngos as $key => $row) {
        $output[$row->id] = $row->firstname;
    }
    
    $shipping_address1_args = wp_parse_args( array(
        'type'       => 'select',
        'options'    => $output,
    ), $fields['donate_section']['_donate_dropdown'] );
    $fields['donate_section']['_donate_dropdown'] = $shipping_address1_args;
    //$fields['shipping']['shipping_first_name']['default'] = 'aaa';
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'donate_section_donate_dropdown' );

Solution

  • Ok! Couple of points in your code!

    First of all, I would give woocommerce_checkout_fields filter hook, a priority. Like so:

    add_filter( 'woocommerce_checkout_fields', 'donate_section_donate_dropdown', 20 );
    

    Then next point is your foreach loop! Change it with following foreach loop:

    foreach ($ngos as $row) {
        $output[$row->id] = $row->firstname;
      };
    

    And the last point is the way you would construct the drop-down menu:

    $fields['shipping']['_donate_dropdown'] = array(
        'type' => 'select',
        'label' => 'Donations',
        'priority' => 25 # use this number to move your drop-down, up and down the list of fields
      );
    
     $fields['shipping']['_donate_dropdown']['options'] = $output;
    

    So the end script for your functions.php would be like this:

    add_filter( 'woocommerce_checkout_fields', 'donate_section_donate_dropdown', 20);
    
    donate_section_donate_dropdown( $fields ) {
        
        global $wpdb;
    
        $ngos = $wpdb->get_results("SELECT * FROM wp_wc_temp_ngo");
        
        $output = array();
        
        $output[0] = "-----------Select a donation option-----------";
        
        foreach( $ngos as $row) {
            $output[$row->id] = $row->firstname;
        }
        
        $fields['shipping']['_donate_dropdown'] = array(
        'type' => 'select',
        'label' => 'Donations',
        'priority' => 25 # use this number to move your drop-down up and down the list of fields
      );
    
        $fields['shipping']['_donate_dropdown']['options'] = $output;
    
        return $fields;
    }
    
    

    Hope this would save you some time and frustrations! I just tested it on my own woocommerce installation and it works fine!