Disable Rules Programmatically in Drupal 7

Rules are a powerful module, which can be used to construct very complex workflows within a Drupal site. Several of contributed modules comes with pre-built rules as part their functionality. Sometimes we may need to disable rules brought by some contributed modules that we used in our site. Disabling a rule through configuration is very easy, just go to rules configuration page, then clicking on 'disable' link work.

Changing just configuration is not good practice as we need to ensure it reaches all developers and different environments like dev, staging etc, especially on large projects having more developers working collaboratively. So we need to ensure that disabling rules also are propagated properly from development to live.

Disabling a rule programmatically is very easy. Create file like MY_MODULE.rules_defaults.inc in your module directory (MY_MODULE to be replaced with your module name). Then implement hook_default_rules_configuration_alter() as below:

/**
 * Implements hook_default_rules_configuration_alter().
 */
function MY_MODULE_default_rules_configuration_alter(&$configs) {
  // Disable rule 'commerce_recurring_cron_generate_orders'
  $configs['commerce_recurring_cron_generate_orders']->active = FALSE;
}

By above code, we are disabling the rule commerce_recurring_cron_generate_orders.

You would need clear the cache after applying the code change.