Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress load a stylesheet through plugin

Tags:

php

wordpress

I have written a WordPress plugin and want to make it include some css stylesheets, I have tried to use the process I usually use in a themes functions.php file...

add_action('wp_enqueue_script','register_my_scripts');

function register_my_scripts(){
    $dir = plugin_dir_path( __FILE__ );
    wp_enqueue_style( $dir . 'css/style1.css');
    wp_enqueue_style( $dir . 'css/style2.css');
}

But this is not loading anything, what am I doing wrong?

like image 530
fightstarr20 Avatar asked Feb 13 '14 16:02

fightstarr20


People also ask

How do I load a stylesheet in WordPress?

Open up a text editor, create a new text file, save it as “custom. css” and upload it into a css folder in your active WordPress theme's folder (i.e. /wp-content/themes/theme/css/) via FTP. Download the functions. php file in your active WordPress theme's folder (i.e. /wp-content/themes/theme/) via FTP.

How do I include a CSS file in a plugin?

Then use: wp_enqueue_style('namespace'); wherever you want the css to load. Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery'); Unless of course you want to use the google repository for jquery.


3 Answers

The hook you need to use is wp_enqueue_scripts, you were missing the 's'.

You're getting the directory path when what you need is the directory URL.

wp_enqueue_style's first parameter is a handle and not the URL.

function wpse_load_plugin_css() {
    $plugin_url = plugin_dir_url( __FILE__ );

    wp_enqueue_style( 'style1', $plugin_url . 'css/style1.css' );
    wp_enqueue_style( 'style2', $plugin_url . 'css/style2.css' );
}
add_action( 'wp_enqueue_scripts', 'wpse_load_plugin_css' );
like image 65
Nathan Dawson Avatar answered Oct 07 '22 06:10

Nathan Dawson


You are using plugin_dir_path which outputs filesystem directory path. Instead you need URL.

Also the first parameter of wp_enqueue_style is $handler name.

Use plugins_url

wp_enqueue_style( 'style1', plugins_url( 'css/style1.css' , __FILE__ ) );

Full code:

add_action('wp_enqueue_scripts','register_my_scripts');

function register_my_scripts(){
    wp_enqueue_style( 'style1', plugins_url( 'css/style1.css' , __FILE__ ) );
    wp_enqueue_style( 'style2', plugins_url( 'css/style2.css' , __FILE__ ) );
}
like image 31
Rahil Wazir Avatar answered Oct 07 '22 06:10

Rahil Wazir


try :

wp_enqueue_style('custom-style', plugins_url( '/css/my-style.css', __FILE__ ), array(),'all'); where plugins_url is relative to plugin base without slash.

like image 32
Obmerk Kronen Avatar answered Oct 07 '22 08:10

Obmerk Kronen