Home > Mobile >  Load a style sheet into a wordpress plugin
Load a style sheet into a wordpress plugin

Time:05-14

So I'm creating a simple plugin for wordpress that will load new block patterns. I've got everything working except for one thing which is enqueueing stylesheets. I've done some research and tried to figure it out but I'm not sure where my code has gone wrong.

/**
 * Load CSS
 */

function sebootscout_enqueue_frontend() {
    wp_enqueue_style( 'sebootscout-block-patterns', plugins_url( 'sebootscout-block-style.css', __DIR__ ), array(), '1.0' );
}
add_action( 'wp_enqueue_scripts', 'sebootscout_enqueue_frontend' );

CodePudding user response:

I always use something like the following. Also making sure I'm actually getting the correct path to the file. The browser developer tools to help show that.

function pl_scripts()
{
  wp_enqueue_style('pl-main', plugin_dir_url(__FILE__) . 'css/pl-main.css', array(), 1.0);
}

add_action('wp_enqueue_scripts', 'pl_scripts');

CodePudding user response:

First you need to register the style

add_action('wp_enqueue_scripts', function () {
    wp_register_style('sebootscout-block-patterns', plugins_url('sebootscout-block-patterns', __FILE__), [], false, 'all');
});

If the file which calls this action is nested and not inside plugin's root folder then replace

plugins_url('sebootscout-block-patterns', __FILE__)

with

plugins_url('sebootscout-block-patterns', dirname(__FILE__))

Finally wherever you want to load the specific registered style

wp_enqueue_style('sebootscout-block-patterns');

Make sure the theme you are testing this on has wp_head(); before </head> on header.php and wp_footer(); before </body> on footer.php

This is because wordpress actually uses those 2 functions to hook your style to the DOM depending on the option to load it on footer or not.

Hope this helps and wish you luck.

  • Related