Search code examples
phpwordpresswoocommercebackendgettext

Using gettext filter for string translation in WooCommerce frontend only


I am trying to use the gettext filter to translate a word in a theme without language files. But I only want to translate it when on mobile wp_is_mobile and only on the frontend.

Using the code below works for the frontend but breaks the site when in admin.

add_filter( 'gettext', 'translate_one_word', 999, 3 );
function translate_one_word( $translated, $text, $domain ) {

    if (is_admin()) return;

        if ( wp_is_mobile() ) {

            $translated = str_ireplace( 'Wrong', 'Right', $translated );

    return $translated;

    }
}

Can someone tell me why my site is breaking in the backend section?


Solution

  • Your code works smoothly in the backend BUT contains 2 errors

    1. You actually return nothing

    This

    if (is_admin()) return;
    

    Should be

    if (is_admin()) return $translated;
    

    1. Always use a return without any condition, if otherwise the condition is not met, nothing can be returned

    This

     if ( wp_is_mobile() ) {
    
        $translated = str_ireplace( 'Wrong', 'Right', $translated );
    
        return $translated;
    
    }
    

    Should be

     if ( wp_is_mobile() ) {
    
        $translated = str_ireplace( 'Wrong', 'Right', $translated );
    
    }
    
    return $translated;
    

    So as the end result, you get:

    function filter_gettext( $translated, $text, $domain ) {
        if ( is_admin() ) {
            return $translated;
        }
    
        if ( wp_is_mobile() ) {
            $translated = str_ireplace( 'Wrong', 'Right', $translated );
        }
        
        return $translated;
    }
    add_filter( 'gettext', 'filter_gettext', 10, 3 );