How to remove CSS file in the header using WordPress functions?

I want to remove a CSS from loading in the header, this is the code that appears:

<link rel='stylesheet' id='my-css'  href='http://test.tld/wp-content/themes/mytheme/my.css?ver=3.5' type='text/css' media='all' />

I tried using these functions but it didn’t work:

wp_dequeue_style('my-css');
wp_deregister_style('my-css');

Is there other ways that the above CSS line can be removed without manually editing it in the template?

Thanks.

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

If your stylesheet is registered and enqueued correctly then…

function dequeue_my_css() {
  wp_dequeue_style('my-css');
  wp_deregister_style('my-css');
}
add_action('wp_enqueue_scripts','dequeue_my_css');
// add a priority if you need it
// add_action('wp_enqueue_scripts','dequeue_my_css',100);

… should remove it. That only works if the stylesheet was registered and/or enqueued with wp_register_style and wp_enqueue_style.

If it is not registered correctly then you will have to figure out what your theme did and undo that. It may require editing the template, depending on how the theme is written.

http://codex.wordpress.org/Function_Reference/wp_dequeue_style

http://codex.wordpress.org/Function_Reference/wp_deregister_style

Method 2

Deregister/Dequeue styles is best practice

https://codex.wordpress.org/Function_Reference/wp_deregister_style
https://codex.wordpress.org/Function_Reference/wp_dequeue_style

But you can use this filter too, to filter out styles with any condition:

add_filter( 'style_loader_src', function($href){
if(strpos($href, "name-of-allowed.css") !== false) {
return $href;
}
return false;
});


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