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 11.3.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' );
$invalidator = wc_get_container()->get( CouponCodeLookupInvalidator::class );
$cache_key = $invalidator->get_cache_key( $code );
$cache_group = $invalidator->get_cache_group();
$ids = wp_cache_get( $cache_key, $cache_group );
/*
* A cached entry is only trusted while all of its coupons are still published, whichever key it
* was cached under. The check describes what the core data store resolves, so any other coupon
* data store, subclasses included, skips it and keeps the write-side invalidation as its only
* layer. Running it there would reject every entry such a store wrote, disabling the lookup
* cache for that site.
*/
$is_stale = false !== $ids
&& 'WC_Coupon_Data_Store_CPT' === $data_store->get_current_class_name()
&& $invalidator->is_lookup_entry_stale( (array) $ids );
if ( false === $ids || $is_stale ) {
$ids = $data_store->get_ids_by_code( $code );
if ( $ids ) {
wp_cache_set( $cache_key, $ids, $cache_group );
} elseif ( $is_stale ) {
$invalidator->invalidate( $code );
}
}
$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 );
}