upgrader_process_complete хук-подіяWP 3.6.0

Спрацьовує після завершення роботи апгрейтера (upgrader). Дозволяє зробити щось після оновлення плагіна, теми, WP, мовного пакета.

Хук спрацьовує вже після того, як оновлені файли оновлюються. Наприклад, при оновленні плагіна, хук спрацює після того, як файли плагіна будуть оновлені.

Не обов’язково використати цей хук рано. Наприклад, його можна використовувати у файлі functions.php теми.

Дивіться також upgrader_package_options .

Використання

add_action( 'upgrader_process_complete', 'wp_kama_upgrader_process_complete_action', 10, 2);

/**
 * Function for `upgrader_process_complete` action-hook.
 *
 * @param WP_Upgrader $upgrader WP_Upgrader instance. У інших контекстах цей пункт буде Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, або Language_Pack_Upgrader instance.
 * @param array $hook_extra Array of bulk item update data.
 *
 * @return void
 */
function wp_kama_upgrader_process_complete_action( $upgrader, $hook_extra ){

	// action...
}
$this
(WP_Upgrader)

Примірник WP_Upgrader .

При різних випадках тут можуть бути об’єкти:

$hook_extra
(масив)

Масив даних елемента, що оновлюється.

  • action (рядок)
    Тип події.
    За замовчуванням: ‘update’

  • type (рядок)
    Тип процесу оновлення. Можливо: plugin, theme, translation, core.

  • bulk (true/false)
    Чи є процес оновлення масовим оновленням (bulk).
    Типово: true

  • plugins (масив)
    Масив шляхів до базових імен основних файлів плагінів.

  • themes (масив)
    Ярлики (слаги) теми.

  • translations (масив)
    Масив даних перекладів.

    • language (рядок)
      Локаль перекладу.

    • type (рядок)
      Переклад. Можливо: plugin, theme, core.

    • slug (рядок)
      Текстовий домен перекладу. Ярлик (склад) теми/плагіна або “default” для основних перекладів.

    • version (рядок)
      Версія теми, плагіна чи ядра.

Приклади

0

#1 Приклад оновлення плагіна і того, які дані отримує хук

Оновлюємо плагін Query Monitor з 3.3.2 до 3.3.3. І записуємо дані змінних усередині хука у файл __upgrader_process_complete_info.txtу корені сайту.

// Тест апгрейду
add_action( 'upgrader_process_complete', 'my_upgrate_function', 10, 2);
function my_upgrate_function( $upgrader_object, $hook_extra ){

	$put = '';
	$put .= '$upgrader_object = '. print_r( $upgrader_object, 1 ) ."nnn";
	$put .= '$hook_extra = '. print_r($hook_extra, 1). "nnn";

	foreach( $hook_extra['plugins'] as $plugin_rel_path ){

		$data = get_plugin_data( WP_PLUGIN_DIR ."/$plugin_rel_path" );

		$put .= "$plugin_rel_path data = ". print_r($data, 1). "nnn";
	}

	file_put_contents( "{$_SERVER['DOCUMENT_ROOT']}/__upgrader_process_complete_info.txt", $put );

}

Отримаємо у файлі __upgrader_process_complete_info.txt(всередині функції-хука):

$upgrader_object = Plugin_Upgrader Object (
	[result] => Array (
			[source] => C:/sites/example.com/www/wp-content/upgrade/query-monitor.3.3.3-VlQkjR/query-monitor/
			[source_files] => Array (
					[0] => assets
					[1] => classes
					[2] => collectors
					[3] => composer.json
					[4] => dispatchers
					[5] => LICENSE
					[6] => output
					[7] => query-monitor.php
					[8] => readme.txt
					[9] => wp-content
				)

			[destination] => C:sitesexample.comwww/wp-content/plugins/query-monitor/
			[destination_name] => query-monitor
			[local_destination] => C:sitesexample.comwww/wp-content/plugins
			[remote_destination] => C:/sites/example.com/www/wp-content/plugins/query-monitor/
			[clear_destination] => 1
		)

	[bulk] => 1
	[strings] => Array (
			[bad_request] => Invalid data provided.
			[fs_unavailable] => Could not access filesystem.
			[fs_error] => Filesystem error.
			[fs_no_root_dir] => Неналежним чином до служби WordPress root directory.
			[fs_no_content_dir] => Неналежним чином вибрати WordPress content directory (wp-content).
			[fs_no_plugins_dir] => Неналежним чином довідка WordPress plugin directory.
			[fs_no_themes_dir] => Неналежним чином до WordPress theme directory.
			[fs_no_folder] => Необхідний місцевий потрібен folder (%s).
			[download_failed] => Download failed.
			[installing_package] => Installing the latest version…
			[no_files] => package contains no files.
			[folder_exists] => Destination folder already exists.
			[mkdir_failed] => Could no create directory.
			[incompatible_archive] => package could not be installed.
			[files_not_writable] => Update може бути налагоджений, щоб бути необхідним для копіювання деяких файлів. Це використовується в основному в послідовному файлі.
			[maintenance_start] => Enabling Maintenance mode…
			[maintenance_end] => Disabling Maintenance mode…
			[up_to_date] => Plugin is at latest version.
			[no_package] => Update package no available.
			[downloading_package] => Downloading update from <span class="code">%s</span>…
			[unpack_package] => Unpacking the update…
			[remove_old] => Зміна останньої версії plugin…
			[remove_old_failed] => Could не remove the old plugin.
			[process_failed] => Plugin update failed.
			[process_success] => Plugin updated successfully.
			[process_bulk_success] => Plugins updated successfully.
		)

	[skin] => WP_Ajax_Upgrader_Skin Object (

			[errors:protected] => WP_Error Object (
					[errors] => Array (
						)

					[error_data] => Array (
						)

				)

			[messages:protected] => Array (
					[0] => Enabling Maintenance mode…
					[1] => Downloading update from https://downloads.wordpress.org/plugin/query-monitor.3.3.3.zip…
					[2] => Unpacking the update…
					[3] => Installing the latest version…
					[4] => Removing the old version of the plugin…
					[5] => Plugin updated successfully.
					[6] => Disabling Maintenance mode…
				)

			[upgrader] => Plugin_Upgrader Object *RECURSION*
			[done_header] =>
			[done_footer] =>
			[result] => Array (
					[source] => C:/sites/example.com/www/wp-content/upgrade/query-monitor.3.3.3-VlQkjR/query-monitor/
					[source_files] => Array (
							[0] => assets
							[1] => classes
							[2] => collectors
							[3] => composer.json
							[4] => dispatchers
							[5] => LICENSE
							[6] => output
							[7] => query-monitor.php
							[8] => readme.txt
							[9] => wp-content
						)

					[destination] => C:sitesexample.comwww/wp-content/plugins/query-monitor/
					[destination_name] => query-monitor
					[local_destination] => C:sitesexample.comwww/wp-content/plugins
					[remote_destination] => C:/sites/example.com/www/wp-content/plugins/query-monitor/
					[clear_destination] => 1
				)

			[options] => Array (
					[url] =>
					[nonce] =>
					[title] =>
					[context] => C:sitesexample.comwww/wp-content
				)

			[plugin_info] => Array (
					[Name] => Query Monitor
					[PluginURI] => https://querymonitor.com/
					[Version] => 3.3.2
					[Description] => The Developer Tools Panel for WordPress.
					[Author] => John Blackbourn
					[AuthorURI] => https://querymonitor.com/
					[TextDomain] => query-monitor
					[DomainPath] => /languages/
					[Network] =>
					[Title] => Query Monitor
					[AuthorName] => John Blackbourn
				)

			[plugin_active] => 1
		)

	[update_count] => 1
	[update_current] => 1
)

$hook_extra = Array (
	[action] => update
	[type] => plugin
	[bulk] => 1
	[plugins] => Array (
		[0] => query-monitor/query-monitor.php
	)
)

query-monitor/query-monitor.php file data = Array (
	[Name] => Query Monitor
	[PluginURI] => https://querymonitor.com/
	[Version] => 3.3.3
	[Description] => The Developer Tools Panel for WordPress. <cite>By <a href="https://querymonitor.com/">John Blackbourn</a>.</cite>
	[Author] => <a href="https://querymonitor.com/">John Blackbourn</a>
	[AuthorURI] => https://querymonitor.com/
	[TextDomain] => query-monitor
	[DomainPath] => /languages/
	[Network] =>
	[Title] => <a href="https://querymonitor.com/">Query Monitor</a>
	[AuthorName] => John Blackbourn
)
0

#2 Повідомлення при оновленні плагіна

Цей міні-плагін демонструє, як відображати сповіщення під час оновлення плагіна.

Відображає різні повідомлення в адмінці (див. admin_notices ): одне під час встановлення плагіна (активації) та інше при оновленні плагіна (для цього використовується поточний хук).

<?php

/**
 * Plugin Name: Upgrader Process Example
 * Plugin URI: https://catapultthemes.com/wordpress-plugin-update-hook-upgrader_process_complete/
 * Description: Just an example of using upgrader_process_complete
 * Version: 1.0.0
 * Автор: Catapult Themes
 * Author URI: https://catapultthemes.com/
 * Text Domain: wp-upe
 * Domain Path: /languages
 */

defined( 'ABSPATH' ) || exit;

add_action( 'upgrader_process_complete', 'wp_upe_upgrade_completed', 10, 2);

add_action( 'admin_notices', 'wp_upe_display_update_notice');
add_action( 'admin_notices', 'wp_upe_display_install_notice');

# При активації. Перехідний режим, щоб ми знали, що щойно активували плагін
register_activation_hook( __FILE__, function() {
	set_transient( 'wp_upe_activated', 1);
} );

/**
 * This function runs when WordPress completes його upgrade process
 * It iterates through each plugin updated to see if ours is included
 *
 * @param array $upgrader_object
 * @param array $options
 */
function wp_upe_upgrade_completed( $upgrader_object, $options ) {

	// The path to our plugin's main file
	$our_plugin = plugin_basename( __FILE__ );

	// If an update has taken place and the updated type is plugins and the plugins element exists
	if( $options['action'] === 'update' && $options['type'] === 'plugin' && isset( $options['plugins'] ) ) {

		// Iterate through the plugins being updated and check if ours is there
		foreach( $options['plugins'] as $plugin ) {

			if( $plugin == $our_plugin ) {
				// Set a transient to record that our plugin has just been updated
				set_transient( 'wp_upe_updated', 1);
			}
		}
	}
}

/**
 * Show a notice to anyone who has just updated this plugin
 * Ця стаття повинна бути відтворена на будь-який час, яка має налаштований Plugin for First Time
 */
function wp_upe_display_update_notice() {

	// Check the transient to see if we've just updated the plugin
	if( get_transient( 'wp_upe_updated' ) ) {

		echo '<div class="notice notice-success"><p>' . __( 'Thanks for updating', 'wp-upe' ) . '</p></div>';

		delete_transient('wp_upe_updated');
	}
}

/**
 * Show a notice to anyone who has just installed the plugin for the first time
 * Ця стаття повинна бути відтворена на будь-який час, яка має досконало updated this plugin
 */
function wp_upe_display_install_notice() {

	// Check the transient to see if we've just activated the plugin
	if( get_transient( 'wp_upe_activated' ) ) {

		echo '<div class="notice notice-success"><p>' . __( 'Thanks for installing', 'wp-upe') . '</p></div>';

		// Delete the transient so we don't keep displaying the activation message
		delete_transient('wp_upe_activated');
	}
}

список змін

З версії 3.6.0Введено.
З версії 3.7.0Added to WP_Upgrader::run() .
З версії 4.6.0$translations був added як можливий argument до $hook_extra .

Де викликається хук

upgrader_process_complete

upgrader_process_complete

upgrader_process_complete

upgrader_process_complete

Де використовується хук у WordPress

wp-admin/includes/admin-filters.php 145

add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20);

wp-admin/includes/admin-filters.php 147

add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0);

wp-admin/includes/admin-filters.php 148

add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0);

wp-admin/includes/admin-filters.php 146

add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0);

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *