1

I would like to add CSS to a page or a shortcode (preferably a shortcode) that would not be dependent on a theme, a plug-in or anything.

I tried adding wp_enqueue_style('[my-css-url]'); to various PHP files but without success. Yet I would expect more proper ways to do it.

I there a way to do that?


This question is not a duplicate of Enqueue Scripts / Styles when shortcode is present That other question is asked and solved in the context of a plug-in. My question clearly state "independant from plug-ins".

1
  • WordPress is designed to execute custom code which leverages it's APIs via the architecture presented by plugins and themes. Slapping wp_enqueue_style() calls in random files is inadvisable and likely to produce undesirable side-effects - or simply erase your changes the next time WordPress updates. Make a small plugin to house your modifications, or let us discuss why you believe you cannot use a plugin.
    – bosco
    Commented Apr 11, 2019 at 20:15

1 Answer 1

2

Simply follow the link to the has_shortcode() documentation in the last answer to the duplicate question. There you'll find:

function custom_shortcode_scripts() {
  global $post;
  if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) {
      wp_enqueue_script( 'custom-script');
  }
}
add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');

For styles this would be:

function custom_shortcode_styles() {
    global $post;
    if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) {
        wp_enqueue_style('custom-shortcode-css', get_template_directory_uri() . '/css/custom-shortcode.css');
    }
}
add_action( 'wp_enqueue_scripts', 'custom_shortcode_styles');

Replace custom-shortcode inside has_shortcode() with the shortcode you are actually looking for, then put that snippet in your functions.php or in your plugin and code on!

2
  • 2
    Keep in mind that this will only load the CSS if the shortcode is inside the post content. If the shortcode is used in a template, widget, custom field or anything else, then the CSS won't load. Commented Apr 11, 2019 at 9:05
  • Thank you, good to know. In my case it's only used in the post content.
    – TTT
    Commented Apr 12, 2019 at 11:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.