Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save woogist/9919480 to your computer and use it in GitHub Desktop.
Save woogist/9919480 to your computer and use it in GitHub Desktop.
An example of using the WooCommerce Admin Custom Order Fields 'wc_admin_custom_order_field_options' filter to return a dynamic set of options. In this sample we're pulling all WordPress terms, for the field which we have named "From Database". Options could be pulled from any other database/table, remote service, or anywhere! To use this code, c…
<?php
/*
* Returns a set of admin custom order field options from the database, rather
* than as configured by the admin
*/
add_filter( 'wc_admin_custom_order_field_options', function( $options, $field ) {
global $wpdb;
// return all the configured WordPress terms as the field options for the field named "From Database"
if ( 'From Database' == $field->label ) {
// clear out any passed options so we can set our own
$options = array();
$results = $wpdb->get_results( "SELECT slug, name FROM {$wpdb->terms} ORDER BY name" );
foreach ( $results as $row ) {
$options[] = array( 'label' => $row->name, 'value' => $row->slug, 'default' => false );
}
}
return $options;
}, 10, 2 );
@Gustaf26
Copy link

Gustaf26 commented Feb 12, 2021

Hi there,

I am trying to add a filter like yours in admin custom order fields plugin, but I don´t know in which file I should paste the snippet.

Can you help me?

It looks like this

`<?php // only copy if needed

/**

  • The wc_admin_custom_order_field_options filter lets you dynamically add options
  • for fields that have them, such as select, multiselect, radio, and checkbox types.
    */

/**

  • Populate options for a field from Shipping Zones

  • @param array $options the field options

  • @param \WC_Custom_Order_Field $field the field instance

  • @return array updated options
    */
    function sv_wc_acof_generate_custom_fields( $options, $field ) {

    // bail unless we're targeting our desired field
    if ( 'Zones' !== $field->label ) {
    return $options;
    }

    // clear out any passed options so we can set our own
    $options = array();

    // get the options we should show
    $zones = WC_Shipping_Zones::get_zones();

    foreach ( $zones as $zone_id => $zone_data ) {

     $zone = WC_Shipping_Zones::get_zone( $zone_id );
    
     $options[] = array( 
     	'label'   => $zone->get_zone_name(),
     	'value'   => $zone->get_id(),
     	'default' => false,
     );
    

    }

    return $options;
    }
    add_filter( 'wc_admin_custom_order_field_options', 'sv_wc_acof_generate_custom_fields', 10, 2 ); `

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment