Translation for a text that is not printed on the screen

How can I enable the translation for a text that is not printed on the screen? I was recently implementing the translation to my plugin and everything worked as expected. But doing the tests I realized that I was missing something. There is a small piece of code in my plugin that creates terms based on a condition, but one of them is a text and I need it to be translated. how can I do? I understand that __ and _e are just for static strings that are printed to screen.

if ( empty ( $cookie ) ) {
    wp_set_post_terms( $post_id, '- Default', 'directory' );
}
else {
    wp_set_post_terms( $post_id, $cookie, 'directory' );
}

(- Default) is what I need to translate

Thanks to whoever can help me

Topic translation multi-language plugin-development plugins Wordpress

Category Web


There is a small piece of code in my plugin that creates terms based on a condition, but one of them is a text and I need it to be translated. how can I do? I understand that __ and _e are for the text that is printed on the screen.

You don't, this is not something WordPress supports out of the box and you've misused the functions, you should not be using __ or _e for dynamic content that came from the database or the user.

__ and _e are a part of the localisation API, intended for static strings in your theme and plugins such as labels.

For example:

<p><?php echo __( 'Name', 'mytextdomain' ); ?>: <?php echo esc_html( $name ); ?></p>

In the above example, trying to pass $name, or a posts title/content into the __ function would be extreme bad practice and a major mistake. Many would consider it a bug.

To translate content from the database such as tags, terms, posts, etc, you need to install a plugin.

As for where it works, __ should work everywhere regardless of context.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.