How to Properly Translate Custom Text in WordPress and WooCommerce Filters
Understanding String Translation in WordPress
When customizing WooCommerce buttons, labels, or archive pages, making sure your custom strings are translation-ready (i18n) is essential for multilingual stores. A frequent mistake developers make when attempting to translate a string inside an existing PHP function is nesting PHP opening and closing tags, like this:
return <?php _e('Pas de Stock', 'veho'); ?>; // Fatal Error!Because you are already inside a PHP execution block, introducing <?php ... ?> tags causes a syntax error. Moreover, the function _e() immediately echoes (prints) the string rather than returning it.
The Solution: Use __() Instead of _e()
In WordPress localization, there are two primary helper functions for simple text translation:
_e( $text, $domain ): Echoes the translated string directly.__( $text, $domain ): Returns the translated string for use in variables, string concatenations, orreturnstatements.
Because the woocommerce_product_add_to_cart_text filter expects you to return a string value, you must use __().
Updated Code Snippet
Here is the corrected, production-ready code you can add to your child theme's functions.php file or a custom site plugin:
add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_archive_custom_cart_button_text', 10, 2 );
function bbloomer_archive_custom_cart_button_text( $text, $product ) {
// Modern WooCommerce passes the $product object as the second argument
if ( ! $product ) {
global $product;
}
if ( $product && ! $product->is_in_stock() ) {
return __( 'Pas de Stock', 'veho' );
}
return $text;
}Key Improvements Explained
- Clean PHP Syntax: Removed unnecessary PHP execution tags within the return statement.
- Returned Translation:
__( 'Pas de Stock', 'veho' )returns the localized version matching your custom text domain (veho) without outputting it prematurely. - Modern Filter Arguments: Modern versions of WooCommerce supply the
$productobject directly as a second argument towoocommerce_product_add_to_cart_text. By passing10, 2intoadd_filter, we can read$productcleanly while falling back toglobal $productfor backwards compatibility.
Making the String Translatable with Translation Plugins
Once you implement __( 'Pas de Stock', 'veho' ), popular translation plugins like WPML, Polylang, or Loco Translate will easily detect the string during a theme or plugin scan, allowing you to provide translations for all configured languages.