0

For example:

  • I have a plugin that adds a box to the page.
  • Box requires CSS file and JS file.
  • Box can be added via shortcode, or via PHP or via widget.

My question is - how to include CSS & JS files only to pages where this box is present?

For JS file it's simple, as it's added to the footer.

But CSS file must be added to the <head> section.

I know that some solutions involve string-parsing post_content and looking for shortcode. But this doesn't help when box is added via Widget or PHP.

Any tips?

Thank you.

1

You can't predict if something will include your box further down the line, so to do it "the right way", you'll need to add your CSS/JS early.

The not-so-right way could be to add output buffering and analyze the output to see if your box got included somewhere, and then add your HTML to the head of the document. It's not clean, and I'd make it optional (and disabled in the default mode so the user has to activate it) and add some explanation as it can get confusing when you wonder why something does/does not work on different pages, and it's often a pain to debug these things if you're not aware of them.

| improve this answer | |
  • Thanks you, I thought so... Wondering why WordPress core doesn't allow doing this, seems like a common scenario and it's not hard to implement it. All you need is to build HTML of the page once and then throw a filter or action that allows to inject JS or CSS files in head. – Marvin3 Oct 20 '17 at 8:19
  • That's true, but it would come with a bit of overhead for buffering everything, parsing HTML etc. That might be why they keep it out of the core, and it's not too hard to build your own. – janh Oct 20 '17 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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