Using WordPress ‘locale_stylesheet()’ PHP function

The locale_stylesheet() WordPress PHP function displays a localized stylesheet link element.

Usage

locale_stylesheet();

Parameters

  • None

More information

See WordPress Developer Resources: locale_stylesheet

Examples

Displaying localized stylesheet in the header

Add the locale_stylesheet() function to the header.php file to include the localized stylesheet in your theme.

<head>
    ...
    locale_stylesheet(); // Displays localized stylesheet link element
</head>

Creating a localized stylesheet for a specific language

  1. Create a new CSS file in your theme’s directory named style-{locale}.css. Replace {locale} with the specific language code (e.g., style-fr_FR.css for French).

  2. Add the locale_stylesheet() function to your header.php file.

<head>
    ...
    locale_stylesheet(); // Displays localized stylesheet link element
</head>

Overriding main stylesheet with localized stylesheet

Use the locale_stylesheet() function to override the main stylesheet with the localized version.

  1. Add the locale_stylesheet() function to your header.php file after the main stylesheet.
<head>
    ...
    <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
    locale_stylesheet(); // Displays localized stylesheet link element
</head>

Conditional localization of stylesheet

Use the locale_stylesheet() function to conditionally load a localized stylesheet based on the site’s language.

  1. Create a new CSS file in your theme’s directory named style-{locale}.css. Replace {locale} with the specific language code (e.g., style-de_DE.css for German).

  2. Add the following code to your header.php file:

<head>
    ...
    if (get_locale() == 'de_DE') {
        locale_stylesheet(); // Displays localized stylesheet link element for German
    }
</head>

Using a custom localized stylesheet path

  1. Create a new CSS file in a custom directory named style-{locale}.css. Replace {locale} with the specific language code (e.g., style-es_ES.css for Spanish).

  2. Add the following code to your header.php file:

<head>
    ...
    add_filter('locale_stylesheet_uri', function($stylesheet_uri, $locale) {
        return get_template_directory_uri() . '/custom-directory/style-' . $locale . '.css';
    }, 10, 2);

    locale_stylesheet(); // Displays localized stylesheet link element with custom path
</head>