最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to add CSS via custom plugin?

programmeradmin1浏览0评论

I am making my first plugin. I create a folder in \wp-content\plugins, 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
Description: Site specific code changes for Quảcầu
*/

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.

I am making my first plugin. I create a folder in \wp-content\plugins, 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
Description: Site specific code changes for Quảcầu
*/

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.

Share Improve this question asked Mar 7, 2021 at 16:19 OokerOoker 3323 silver badges23 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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__ );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论