# activate_plugin()

URL: https://chugunov.pro/api-wordpress/functions/activate_plugin/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 2.5.0.

## Сигнатура

```php
activate_plugin( string $plugin, string $redirect = '', bool $network_wide = false, bool $silent = false ): null|WP_Error
```

## Описание

Уже активированный плагин не будет активирован повторно.
Работа устроена так: перед попыткой подключить файл плагина перенаправление устанавливается на страницу ошибки. Если плагин завершается сбоем, перенаправление не будет перезаписано сообщением об успехе. Кроме того, при ошибке плагина опции не обновляются, а хук активации не вызывается.
Следует отметить, что приведённый ниже код никак не предотвращает ошибки внутри файла. Этот код не следует использовать в других местах для воспроизведения «песочницы», работа которой основана на перенаправлении.
{@source 13 1}
Если обнаружены ошибки или выведен какой-либо текст, он будет перехвачен, чтобы перенаправление на успех обновило перенаправление на ошибку.

## Параметры

- `$plugin` `string` — обязательный. Путь к файлу плагина относительно каталога плагинов.
- `$redirect` `string` — необязательный, по умолчанию `''`. URL для перенаправления.
- `$network_wide` `bool` — необязательный, по умолчанию `false`. Включить ли плагин для всех сайтов сети или только для текущего сайта. Только для Multisite.
- `$silent` `bool` — необязательный, по умолчанию `false`. Предотвращать ли вызов хуков активации.

## Возвращаемое значение

`null|WP_Error` — WP_Error

## Исходный код

Файл: `wp-admin/includes/plugin.php:641`

```php
function activate_plugin( $plugin, $redirect = '', $network_wide = false, $silent = false ) {
	$plugin = plugin_basename( trim( $plugin ) );

	if ( is_multisite() && ( $network_wide || is_network_only_plugin( $plugin ) ) ) {
		$network_wide        = true;
		$current             = get_site_option( 'active_sitewide_plugins', array() );
		$_GET['networkwide'] = 1; // Back compat for plugins looking for this value.
	} else {
		$current = get_option( 'active_plugins', array() );
	}

	$valid = validate_plugin( $plugin );
	if ( is_wp_error( $valid ) ) {
		return $valid;
	}

	$requirements = validate_plugin_requirements( $plugin );
	if ( is_wp_error( $requirements ) ) {
		return $requirements;
	}

	if ( $network_wide && ! isset( $current[ $plugin ] )
		|| ! $network_wide && ! in_array( $plugin, $current, true )
	) {
		if ( ! empty( $redirect ) ) {
			// We'll override this later if the plugin can be included without fatal error.
			wp_redirect( add_query_arg( '_error_nonce', wp_create_nonce( 'plugin-activation-error_' . $plugin ), $redirect ) );
		}

		ob_start();

		// Load the plugin to test whether it throws any errors.
		plugin_sandbox_scrape( $plugin );

		if ( ! $silent ) {
			/**
			 * Fires before a plugin is activated.
			 *
			 * If a plugin is silently activated (such as during an update),
			 * this hook does not fire.
			 *
			 * @since 2.9.0
			 *
			 * @param string $plugin       Path to the plugin file relative to the plugins directory.
			 * @param bool   $network_wide Whether to enable the plugin for all sites in the network
			 *                             or just the current site. Multisite only. Default false.
			 */
			do_action( 'activate_plugin', $plugin, $network_wide );

			/**
			 * Fires as a specific plugin is being activated.
			 *
			 * This hook is the "activation" hook used internally by register_activation_hook().
			 * The dynamic portion of the hook name, `$plugin`, refers to the plugin basename.
			 *
			 * If a plugin is silently activated (such as during an update), this hook does not fire.
			 *
			 * @since 2.0.0
			 *
			 * @param bool $network_wide Whether to enable the plugin for all sites in the network
			 *                           or just the current site. Multisite only. Default false.
			 */
			do_action( "activate_{$plugin}", $network_wide );
		}

		if ( $network_wide ) {
			$current            = get_site_option( 'active_sitewide_plugins', array() );
			$current[ $plugin ] = time();
			update_site_option( 'active_sitewide_plugins', $current );
		} else {
			$current   = get_option( 'active_plugins', array() );
			$current[] = $plugin;
			sort( $current );
			update_option( 'active_plugins', $current );
		}

		if ( ! $silent ) {
			/**
			 * Fires after a plugin has been activated.
			 *
			 * If a plugin is silently activated (such as during an update),
			 * this hook does not fire.
			 *
			 * @since 2.9.0
			 *
			 * @param string $plugin       Path to the plugin file relative to the plugins directory.
			 * @param bool   $network_wide Whether to enable the plugin for all sites in the network
			 *                             or just the current site. Multisite only. Default false.
			 */
			do_action( 'activated_plugin', $plugin, $network_wide );
		}

		if ( ob_get_length() > 0 ) {
			$output = ob_get_clean();
			return new WP_Error( 'unexpected_output', __( 'The plugin generated unexpected output.' ), $output );
		}

		ob_end_clean();
	}

	return null;
}
```

## История изменений

- 5.2.0 — Test for WordPress version and PHP version compatibility.
- 2.5.0 — Introduced.

## Связанные

Использует: [`validate_plugin_requirements`](https://chugunov.pro/api-wordpress/functions/validate_plugin_requirements/), [`validate_plugin`](https://chugunov.pro/api-wordpress/functions/validate_plugin/), [`is_network_only_plugin`](https://chugunov.pro/api-wordpress/functions/is_network_only_plugin/), [`plugin_sandbox_scrape`](https://chugunov.pro/api-wordpress/functions/plugin_sandbox_scrape/), [`wp_redirect`](https://chugunov.pro/api-wordpress/functions/wp_redirect/), [`plugin_basename`](https://chugunov.pro/api-wordpress/functions/plugin_basename/), [`update_site_option`](https://chugunov.pro/api-wordpress/functions/update_site_option/), [`__`](https://chugunov.pro/api-wordpress/functions/__/), [`wp_create_nonce`](https://chugunov.pro/api-wordpress/functions/wp_create_nonce/), [`is_multisite`](https://chugunov.pro/api-wordpress/functions/is_multisite/), [`add_query_arg`](https://chugunov.pro/api-wordpress/functions/add_query_arg/), [`do_action`](https://chugunov.pro/api-wordpress/functions/do_action/), [`get_site_option`](https://chugunov.pro/api-wordpress/functions/get_site_option/), [`update_option`](https://chugunov.pro/api-wordpress/functions/update_option/), [`get_option`](https://chugunov.pro/api-wordpress/functions/get_option/), [`is_wp_error`](https://chugunov.pro/api-wordpress/functions/is_wp_error/), `WP_Error::__construct`.
Используется в: [`wp_ajax_activate_plugin`](https://chugunov.pro/api-wordpress/functions/wp_ajax_activate_plugin/), `WP_REST_Plugins_Controller::handle_plugin_status`, [`activate_plugins`](https://chugunov.pro/api-wordpress/functions/activate_plugins/).

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/activate_plugin/
