WC_Helper::set_subscription_auto_update
Turn auto-updates on or off for the plugin or theme backing a subscription.
Writes the same auto_update_plugins / auto_update_themes site options WordPress core's Plugins and Themes screens write, so the change is identical to making it there.
Method of the class: WC_Helper{}
No Hooks.
Returns
void. Nothing (null).
Usage
$result = WC_Helper::set_subscription_auto_update( $product_key, $enabled ): void;
- $product_key(string) (required)
- Subscription product key.
- $enabled(true|false) (required)
- Whether auto-updates should be on.
Changelog
| Since 11.2.0 | Introduced. |
WC_Helper::set_subscription_auto_update() WC Helper::set subscription auto update code WC 11.2.1
public static function set_subscription_auto_update( string $product_key, bool $enabled ): void {
$subscription = self::get_subscription( $product_key );
if ( ! is_array( $subscription ) ) {
throw new Exception( esc_html__( 'There is no subscription for this product.', 'woocommerce' ) );
}
// Resolved the same way the row itself is, by zip_slug against every installed product.
// _get_local_from_product_id() only sees products carrying a Woo header, which misses the
// WooCommerce.com products distributed through WordPress.org.
$local = self::get_subscription_local_data( $subscription );
if ( empty( $local['installed'] ) ) {
throw new Exception( esc_html__( 'This subscription has no installed product to update.', 'woocommerce' ) );
}
$is_theme = 'theme' === $local['type'];
// auto_update_themes is keyed by stylesheet, auto_update_plugins by plugin file.
$item_key = $is_theme ? (string) $local['slug'] : (string) $local['path'];
if ( '' === $item_key ) {
throw new Exception( esc_html__( 'This subscription has no installed product to update.', 'woocommerce' ) );
}
$auto_update = $is_theme
? self::get_theme_auto_update_data( $item_key )
: self::get_plugin_auto_update_data( $item_key );
if ( ! $auto_update['auto_update_manageable'] ) {
throw new Exception( esc_html__( "Auto-updates for this product can't be changed from here.", 'woocommerce' ) );
}
$all_items = $is_theme ? self::get_all_theme_keys() : self::get_all_plugin_keys();
if ( ! in_array( $item_key, $all_items, true ) ) {
throw new Exception( esc_html__( 'The product for this subscription is no longer installed.', 'woocommerce' ) );
}
$option = $is_theme ? 'auto_update_themes' : 'auto_update_plugins';
$auto_updates = (array) get_site_option( $option, array() );
if ( $enabled ) {
$auto_updates[] = $item_key;
$auto_updates = array_unique( $auto_updates );
} else {
$auto_updates = array_diff( $auto_updates, array( $item_key ) );
}
// Drop entries for products deleted since the option was last written, as core does.
$auto_updates = array_intersect( $auto_updates, $all_items );
update_site_option( $option, array_values( $auto_updates ) );
}