csswordpressenqueue

Wordpress - enqueue style after all others or after certain styles


I'm writing a plugin for Wordpress which I need to enqueue style files in front end. But when I do this some other plugins like vs_composer add their styles files after my plugin and override my codes. So I think there are two options to deal with this situation. First one is to make some CSS rules !important which I think is not a professional way. The other option is to load my plugin CSS files after all others; But is it possible? I guess this goal is not achievable by using $deps parameter in wp_enqueue_style as it doesn't load files if dependency files don't exist.


Solution

  • You could enqueue your stylesheets by hooking into wp_head, which prints data in the head tag on the front end.

    function enqueue_styles() {
      wp_enqueue_style( 'frontend-style', plugin_dir_url( __FILE__ ) . 'styles.css' );
    }
    
    add_action( 'wp_head', 'enqueue_styles' ); // default priority: 10
    

    If you need to output your stylesheets later, you can lower the priority.

    For example,

    add_action( 'wp_head', 'enqueue_styles', 20 ); 
    

    Alternatively, you could change your selectors to be more specific, so your CSS rules take precedence over vs_composer's.

    div {}
    div.my-class {} /* more specific */
    body div.my-class {} /* even more specific */
    

    Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. [ā€¦] Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element.

    ā€” MDN source