How to connect Tailwind CSS CDN scripts in WordPress?

To integrate Tailwind CSS CDN scripts and pass configuration via PHP in WordPress, you need to follow these steps:

  1. Use the wp_enqueue_scripts hook to load Tailwind CSS and your custom configuration script.
  2. Rebuild the tailwind.config via a PHP array, and then convert it into JSON format for use in JavaScript.

Here’s an example of the code:

function enqueue_tailwind_cdn() {
    // Enqueue Tailwind CSS via CDN
    wp_enqueue_script('tailwind-cdn', 'https://cdn.tailwindcss.com', array(), null, true);

    // Create the Tailwind configuration in PHP
    $tailwind_config = array(
        'theme' => array(
            'extend' => array(
                'colors' => array(
                    'clifford' => '#da373d', // Your custom colors
                ),
            ),
        ),
    );

    // Convert the array to JSON
    $tailwind_config_json = json_encode($tailwind_config);

    // Add an inline script to configure Tailwind with the settings
    wp_add_inline_script('tailwind-cdn', "
        tailwind.config = $tailwind_config_json;
    ");
}

add_action('wp_enqueue_scripts', 'enqueue_tailwind_cdn');

Explanation:

  1. Enqueue Tailwind CSS via CDN:
    • wp_enqueue_script('tailwind-cdn', 'https://cdn.tailwindcss.com', array(), null, true); — This loads Tailwind CSS from the CDN.
    • The true parameter in wp_enqueue_script specifies that the script should be loaded at the bottom of the page.
  2. Tailwind configuration via PHP array:
    • We create a PHP array with the configuration, where in the extend section we add your custom styles (e.g., custom color clifford).
  3. Converting the array to JSON:
    • We use json_encode() to convert the PHP array into JSON, which can be embedded into the JavaScript.
  4. Adding the configuration script to the page:
    • wp_add_inline_script inserts the JSON configuration directly into the page, after the main Tailwind script.

This code will load Tailwind CSS via the CDN and configure the theme, extending it with custom colors or other settings.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more