How to add CSS via custom plugin?

I am making my first plugin. I create a folder in wp-contentplugins, create a test.css and a test.php file.

Here is my test.css:

body {
    background-color: red !important;
}

Here is my test.php (Taken from Theme Developer Handbook):

<?php
/*
Plugin Name: Site Plugin for Quảcầu.com
Description: Site specific code changes for Quảcầu.com
*/

function add_theme_scripts() {
  wp_enqueue_style( 'style', get_stylesheet_uri() );
 
  wp_enqueue_style( 'slider', get_template_directory_uri() . 'test.css', array(), '1.1', 'all');
}

add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

But the color doesn’t change. Do you know why? Of course I have activated it.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here’s your problem:

  wp_enqueue_style( 'style', get_stylesheet_uri() );
 
  wp_enqueue_style( 'slider', get_template_directory_uri() . 'test.css', array(), '1.1', 'all');

Neither of those files are in your theme. get_stylesheet_uri refers to the style.css that has the themes name etc, and get_template_directory_uri is the URL of the parent theme. Neither of those are your plugin folder.

You can confirm this by looking at the browser dev tools and seeing an error in the console that it tried to load a test.css from your themes folder and failed.

Instead use plugins_url.

e.g.

plugins_url( 'images/wordpress.png', __FILE__ )

Where the first parameter is the path to the file in your plugin folder, and the second parameter is the main plugin file location on the server.

So this:

get_template_directory_uri() . 'test.css'

becomes:

plugins_url( 'test.css', __FILE__ );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x