Preparing a string in an array for localization

I’m working on a WordPress plugin and want to make sure that all text that is displayed is prepared for localization. I’m having trouble localizing the text that resides inside an array.

For instance, I have the following code inside a class

var $control_type_default = array(
    array(
        'key' => 'automatic',
        'value' => 'Automatic'
    )
);

var $control_types = array(
    array(
        'key' => 'manual',
        'value' => 'Manual'
    )
);

function process_class_vars()
{
    // Add default control type value to beginning of control types array
    $this->control_types = array_merge($this->control_type_default, $this->control_types);

    // Prepare values for localization
    $temp_array = array();
    foreach ($this->control_types as $control_type_array => $values) 
    {
        $temp_array[] = array(
            'key' => $values['key'],
            'value' => __($values['value'], 'my_plugin')
        );
    }
    $this->control_type = $temp_array;
}

Note that the “process_class_vars” function is called by the constructor. As you can see, I am attempting to pass the value in the array through the __() function (As a side note, I’m doing this with the function “process_class_vars” function instead of when I initially create the arrays because passing that function when I created the arrays initially threw an error).

The problem is that when I run this through a .po generator, the “Automatic” and “Manual” string are completely missed. How can these values be processed correctly?

1 Answer
1

You can’t do that, at least not from a GUI translation helper app, because these are set to pick up strings from standard functions like __(), _e etc, they can’t read variables (including string variables)

Instead try:

var $control_types = array(
    array(
        'key' => 'manual',
        'value' => __('Manual', 'yourtextdomain')
    )
);

But if $control_types is a static variable from a class then you won’t be able to assign the return value of a function as it’s value. Why not make it a normal variable inside the process_class_vars() method? Or just make it a function:

public static function control_types(){
 return
    array(
        'manual' => __('Manual', 'yourtextdomain'),
        ...
    )
);

...
foreach ($this->control_types() as $control_type => $label) 
{
    // I'm pretty sure you don't need 'key' / and 'value' as key name here either...
    $temp_array[] = array(
        'key' => $control_type,
        'value' => $label,
    );
}

Leave a Comment