Skip to content

Instantly share code, notes, and snippets.

@MrSwed
Created April 7, 2022 14:01
Show Gist options
  • Save MrSwed/dce4b3dd462eb18d3e7a198d8dfd4321 to your computer and use it in GitHub Desktop.
Save MrSwed/dce4b3dd462eb18d3e7a198d8dfd4321 to your computer and use it in GitHub Desktop.
Get a list of currently available shipping services in woocommerce
if ( ! function_exists( "get_shippings" ) ) {
/**
* Get a list of currently available shipping services.
* https://gist.github.com/MrSwed/dce4b3dd462eb18d3e7a198d8dfd4321
*
* @param mixed $filter instance_id if number, id if string, call it if it is function or array of fields for filter
*
* @return array
*/
function get_shippings( $filter = array() ) {
if ( ! class_exists( 'WC_Shipping_Zones' ) ) {
return [];
}
$key = 'WC_Shipping_Zones::get_zones()';
$zones = wp_cache_get( $key, __CLASS__ );
if ( $zones === false ) {
$zones = WC_Shipping_Zones::get_zones();
wp_cache_set( $key, $zones, __CLASS__ );
}
$shippings = array_reduce( $zones, function ( $r, $i ) use ( $filter ) {
$methods = $i["shipping_methods"];
if ( ! empty( $filter ) ) {
if ( is_callable( $filter ) ) {
$methods = array_filter( $methods, $filter );
} else if ( is_numeric( $filter ) ) {
$filter = array( "instance_id" => $filter );
} else if ( is_string( $filter ) ) {
$filter = array( "id" => $filter );
}
if ( is_array( $filter ) ) {
$methods = array_filter( $methods, function ( $method ) use ( $filter ) {
foreach ( $filter as $key => $key_arg ) {
if ( ! isset( $method->$key )
or ( ( is_string( $key_arg ) or is_numeric( $key_arg ) ) and $method->$key !== $key_arg )
or ( ( is_array( $key_arg ) and ! in_array( $method->$key, $key_arg ) ) ) ) {
return false;
}
}
return true;
} );
}
}
return $r + array_combine(
array_column( $methods, "instance_id" ),
array_column( $methods, "title" ) );
}, array() );
return $shippings;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment