钩子文档

upgrader_post_install

💡 云策文档标注

概述

upgrader_post_install 是一个 WordPress 过滤器钩子,用于在安装或升级包完成后修改安装响应。它允许开发者在安装过程中执行自定义操作,例如区分首次安装和升级。

关键要点

  • 过滤器在安装完成后触发,可修改安装响应。
  • 参数包括 $response(布尔值安装响应)、$hook_extra(额外参数数组)和 $result(安装结果数据数组)。
  • 常用于插件或主题升级时执行特定逻辑,如更新设置或显示通知。

代码示例

add_filter( 'upgrader_post_install', 'wpdocs_plugin_update', 10, 3 );
function wpdocs_plugin_update( $response, $extras, $result ) {
  if ( isset( $result['destination_name'] ) && 'wpdocs-plugin-slug' === $result['destination_name'] && $response ) {
    $my_settings           = get_option( 'wpdocs-plugin-options', array() );
    $my_settings['update'] = true;
    update_option( 'wpdocs-plugin-options', $my_settings );
  }

  return $response;
}

注意事项

此过滤器自 WordPress 2.8.0 版本引入,主要用于 WP_Upgrader::install_package() 方法中。使用时需确保正确处理参数和返回值,以避免影响安装流程。


📄 原文内容

Filters the installation response after the installation has finished.

Parameters

$responsebool
Installation response.
$hook_extraarray
Extra arguments passed to hooked filters.
$resultarray
Installation result data.

Source

$res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can use this filter to distinguish between your plugin being installed for the first time or an upgrade over an existing installation. This could be useful in the scenario where you need to publish some admin notices to users on specific version upgrades.

    add_filter( 'upgrader_post_install', 'wpdocs_plugin_update', 10, 3 );
    function wpdocs_plugin_update( $response, $extras, $result ) {
      if ( isset( $result['destination_name'] ) && 'wpdocs-plugin-slug' === $result['destination_name'] && $response ) {
        $my_settings           = get_option( 'wpdocs-plugin-options', array() );
        $my_settings['update'] = true;
        update_option( 'wpdocs-plugin-options', $my_settings );
      }
    
      return $response;
    }

    you can then consult your plugin settings to see if this is an updated version.