acf-options-for-polylang icon indicating copy to clipboard operation
acf-options-for-polylang copied to clipboard

Option/function to retrieve option in a specific language?

Open romanklabal opened this issue 6 years ago • 2 comments
trafficstars

Hi, first of all, thank you very much for the much needed plugin that allows ACF Options to be linked with Polylang, I am happily using it on several sites already.

My question/feature request: is there a way to retrieve an option in a different language than the one currently being used on the frontend? Say I am browing the English version of the website, but I need to get an option value of a German version. I could naturally do it via WPDB, but I am hoping there is/could be another way, maybe as a param to a method, where the default value would be the currently used language?

Something along the lines if beapi_get_option($name, $language = pll_current_language()) {}

romanklabal avatar May 22 '19 10:05 romanklabal

Hi @rklabal,

This is a pretty good idea, thx for the request.

Something like a helper to get options value from an other language than the current one.

MaximeCulea avatar May 22 '19 10:05 MaximeCulea

I was able to get this to work like this:

/**
 * Get a value from an ACF options page for a specific locale
 * The locale must adhere to the WordPress standard (e.g. `en_GB` or `de_DE_formal`...)
 *
 * @param string $key           The ACF field key
 * @param string $options_id    The ACF options page's post_id
 * @param string $locale        The locale.
 * @param array $args {
 *   Optional array of arguments. Will be forwarded to ACF's get_field
 *
 *   @param boolean $format_value   Should the value be formatted?
 *   @param boolean $escape_html    Should HTML be escaped?
 * }
 */
function get_options_field_for_locale(
    string $key,
    string $options_id,
    string $locale,
    array $args = []
): mixed {
    
    $locale_filter = fn() => $locale;

    // Overwrite the current locale
    add_filter('acf/settings/current_language', $locale_filter);

    // Allow passing additional optional args to ACF's get_field()
    $args = array_merge([
        'format_value' => true,
        'escape_html' => false
    ], $args);

    $result = get_field($key, $options_id, ...$args);

    // reset the filter
    remove_filter('acf/settings/current_language', $locale_filter);

    return $result;
}

Usage

$en = get_options_field_for_locale(
    key: 'my_field',
    options_id: 'site-options',
    locale: 'en_GB',
);
$de = get_options_field_for_locale(
    key: 'my_field',
    options_id: 'site-options',
    locale: 'de_DE_formal',
);
var_dump(compact('en', 'de'));

Result

array(2) {
  ["en"] => "English Value"
  ["de"] => "Deutscher Wert"
}

hirasso avatar Feb 26 '24 09:02 hirasso