You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中__(‘Save Change’)与_e(‘Save Change’)函数的作用及使用场景咨询

Hey there! I’ve used these two WordPress localization functions constantly while building themes and plugins, so let’s break them down clearly for you.

What do __() and _e() do?

Both functions are core to WordPress’s localization system—they let you make your code ready for translation into other languages, so your themes/plugins can reach a global audience. The main difference is how they handle the translated text.

__(): Returns a translated string (doesn’t output it)

This function takes a string and its text domain, finds the corresponding translation (if one exists), and returns that translated string without printing it to the page.

When to use it:

  • You need to store the translated text in a variable for later use
  • You’re using the text inside an HTML attribute (like a button’s value or alt text)
  • You need to modify or escape the text before displaying it

Example code:

// Store translated text in a variable
$save_button_label = __('Save Changes', 'my-custom-theme');

// Use the variable in a button (with escaping for security)
echo '<button type="submit">' . esc_html($save_button_label) . '</button>';

// Use directly in an HTML attribute
echo '<img src="icon.png" alt="' . esc_attr(__('Save Settings Icon', 'my-custom-theme')) . '">';

_e(): Outputs a translated string directly

This function does the exact same translation work as __(), but instead of returning the string, it immediately prints it to the browser. Think of it as a shortcut for echo __('Your Text', 'text-domain').

When to use it:

  • You want to display text directly on the page without any extra processing
  • You’re adding plain text inside HTML elements (like paragraph text, labels, or form instructions)

Example code:

// Directly print a success message
<p><?php _e('Your changes have been saved successfully!', 'my-custom-plugin'); ?></p>

// Use in a form label
<label for="email-address"><?php _e('Email Address', 'my-custom-plugin'); ?></label>

Critical Note: Don’t Forget the Text Domain

In both examples, you’ll notice the second parameter (like 'my-custom-theme' or 'my-custom-plugin'). This is your text domain—a unique identifier for your theme/plugin’s translation files. Without it, WordPress won’t know where to look for translations, so these functions will just return the original English text.

Key Takeaway
  • Use __() when you need to capture or modify the translated text first
  • Use _e() when you just need to display the text right away

It’s all about convenience and what you need to do with the translated string—both serve the same core localization purpose, just in different ways.

内容的提问来源于stack exchange,提问作者Tautve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:17:36