wc_get_coupon_id_by_code()
Get coupon ID by code.
Hooks from the function
Returns
Int.
Usage
wc_get_coupon_id_by_code( $code, $exclude );
- $code(string) (required)
- Coupon code.
- $exclude(int)
- Used to exclude an ID from the check if you're checking existence.
Changelog
| Since 3.0.0 | Introduced. |
wc_get_coupon_id_by_code() wc get coupon id by code code WC 10.7.0
function wc_get_coupon_id_by_code( $code, $exclude = 0 ) {
if ( StringUtil::is_null_or_whitespace( $code ) ) {
return 0;
}
$data_store = WC_Data_Store::load( 'coupon' );
// Coupon code allows spaces, which doesn't work well with some cache engines (e.g. memcached).
$hashed_code = md5( wc_strtolower( $code ) );
$cache_key = WC_Cache_Helper::get_cache_prefix( 'coupons' ) . 'coupon_id_from_code_' . $hashed_code;
$ids = wp_cache_get( $cache_key, 'coupons' );
if ( false === $ids ) {
$ids = $data_store->get_ids_by_code( $code );
if ( $ids ) {
wp_cache_set( $cache_key, $ids, 'coupons' );
}
}
$ids = array_diff( array_filter( array_map( 'absint', (array) $ids ) ), array( $exclude ) );
return apply_filters( 'woocommerce_get_coupon_id_from_code', absint( current( $ids ) ), $code, $exclude );
}