2

I'm working on a simple invoice plugin with which I'll create my invoices for my clients. The working plugin can be found here:

https://github.com/dingo-d/invoice-create-plugin

Now I'm basically done with it. You create your invoice, set all things up, and in the invoice you can click to download it, and you'll get a pdf created in the pdf folder in the plugin.

This pdf will be in English, since I did it in English. But I also created a Croatian .mo and .po translations.

The idea is that I can choose in which language I'll create the pdf file.

I searched a bit, and only found this: https://stackoverflow.com/questions/9225380/using-gettext-to-translate-an-email-inside-an-ajax-call

But I'm not really sure how to use this.

Should I just use setlocale() before creating my pdf or? How can I force translation of the created pdf if I have .mo files available? All the strings are translatable ofc.

Can this be done?

EDIT

So far these things worked:

Setting the whole admin language to Croatian, influenced the plugin, and the pdf generated.

This is kinda a lousy solution because I'd need to change language every time I want to get out a pdf.

Hooking to locale filter

add_filter( 'locale', 'mbd_change_locale', 10 );

function mbd_change_locale() {
    return 'hr_HR';
}

Which also affects everything.

Is there a way for me to use this filter from inside the AJAX call to change the locale and force a translation?

1

Solved by adding

if ( isset( $_POST['language'] ) ) { // Input var okay.

    add_filter( 'locale', 'mbd_set_my_locale' );
    /**
     * Set locale based on the $_POST choice.
     *
     * @param  string $locale Locale code.
     * @return string         Selected locale code.
     */
    function mbd_set_my_locale( $locale  ) {
        $language = sanitize_text_field( wp_unslash( $_POST['language'] ) ); // Input var okay.

        if ( 'hr' === $language ) {
            $locale = 'hr';
        } else {
            $locale = 'en';
        }
        return $locale;
    }
}

Before initializing the main plugin class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.