2
votes

I'm at my wit's end here... here is the code I use to try and get a CSS file to work in my WordPress plugin:

add_action('wp_enqueue_scripts', 'initial_admin_links_hide_stylesheet');

function initial_admin_links_hide_stylesheet() {
    wp_enqueue_style( 'prefix-style', plugins_url('initial_hide_admin_links.css', __FILE__));   
}

Then I call the function by using this line of code:

initial_admin_links_hide_stylesheet();

If I comment out the call to the function I receive no notices. If I leave it uncommented, the notice I receive is:

Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.) in /home2/jakereva/public_html/wp-includes/functions.php on line 3547

As far as I can tell, the code has been written correctly, but I absolutely cannot get that notice to go away when I call the function. Help! Thanks in advance.

2

2 Answers

3
votes
add_action('wp_enqueue_scripts', 'initial_admin_links_hide_stylesheet');

This tells Wordpress to hook the script into the process for you. There is no need to call the function manually.

Make sure you have wp_head() and wp_footer() calls in your theme files where appropriate or it want be added

/**
 * Proper way to enqueue scripts and styles
 */
function theme_name_scripts() {
    wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
0
votes

Change hook name to wp_head. This will enqueue style in header.

Check the WordPress action reference to see what actions being called. https://codex.wordpress.org/Plugin_API/Action_Reference

In front you can use wp_head. In admin pages: admin_enqueue_scripts