钩子文档

switch_locale

💡 云策文档标注

概述

switch_locale 是一个 WordPress 动作钩子,在切换语言环境时触发,允许开发者执行自定义逻辑。它提供两个参数:新的语言环境和可选的用户 ID。

关键要点

  • 触发时机:当 WordPress 切换语言环境(locale)时自动触发。
  • 参数:$locale(字符串,新语言环境)和 $user_id(整数或 false,用户 ID,可选)。
  • 用途:可用于更新用户元数据、记录日志或显示通知等自定义操作。
  • 版本历史:从 WordPress 4.7.0 引入,6.2.0 版本添加了 $user_id 参数。

代码示例

// Define a callback function to execute when the switch_locale action is triggered
function wpdocs_switch_locale_callback( $locale, $user_id ) {
    // Perform custom logic or tasks here based on the locale and user ID
    
    // Example: Update user meta with the new locale
    update_user_meta( $user_id, 'locale', $locale );
    
    // Example: Display a success message
    echo 'Locale switched to: ' . $locale;
}

// Hook the callback function to the switch_locale action
add_action( 'switch_locale', 'wpdocs_switch_locale_callback', 10, 2 );

注意事项

  • 确保回调函数正确处理 $user_id 参数,因为它可能为 false。
  • 使用 add_action 时,优先级和参数数量(如 10, 2)需根据需求设置。

📄 原文内容

Fires when the locale is switched.

Parameters

$localestring
The new locale.
$user_idfalse|int
User ID for context if available.

Source

do_action( 'switch_locale', $locale, $user_id );

Changelog

Version Description
6.2.0 The $user_id parameter was added.
4.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Basic example of the hook for below operations.

    1. Updating the user meta with the new locale using the update_user_meta() function.
    2. Displaying a success message indicating the switched locale.
    // Define a callback function to execute when the switch_locale action is triggered
    function wpdocs_switch_locale_callback( $locale, $user_id ) {
        // Perform custom logic or tasks here based on the locale and user ID
        
        // Example: Update user meta with the new locale
        update_user_meta( $user_id, 'locale', $locale );
        
        // Example: Display a success message
        echo 'Locale switched to: ' . $locale;
    }
    
    // Hook the callback function to the switch_locale action
    add_action( 'switch_locale', 'wpdocs_switch_locale_callback', 10, 2 );