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".

closed as too broad by Jacob Peattie, cjbj, bosco, Rick Hellewell, Christine Cooper Apr 22 at 11:15

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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 Apr 11 at 20:15
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
    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. – Jacob Peattie Apr 11 at 9:05
  • Thank you, good to know. In my case it's only used in the post content. – TTT Apr 12 at 11:03

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