Enqueue and load a CSS file *only* if string in content matches? (8 posts)

  1. archon810
    Posted 6 years ago #

    This is a 'writing a plugin' question.

    I have a CSS and JS file that I only want to include (as they're quite big) if any post on the current page (index, single, search, etc) contains a specific shortcode. To simplify, let's say I want to only load it if the post content contains "FOOBAR". Of course, I'd like to use wp_enqueue_style() and wp_enqueue_script() - the proper way to do it.

    Is this possible?

    The problem is that the header is printed before the content, so as far as I understand it'll be too late. If wordpress made 2 passes - the first one to determine everything and run all the hooks, and the second one to print everything, it'd be easier.

    The wp_print_styles hook is triggered outside of the content loop and is just a hook, not a filter. the_content filter is already too late, as far as I can tell.

    Any ideas, guys? This is a really common optimization a lot of plugins could use (don't trash every page with your css/js unless needed).


  2. Janis Elsts
    Posted 6 years ago #

    I've never though about this before, but after some doc-reading it appears to be possible. You just need to hook the "the_posts" filter. Here's a very basic example :

    add_filter('the_posts', 'test_the_posts');
    function test_the_posts($posts){
    	if ( empty($posts) ) return $posts;
    	$shortcode_found = false;
    	foreach ( $posts as $post ){
    		if ( stripos($post->post_content, '[my_code]') ){
    			$shortcode_found = true;
    	if ( $shortcode_found ){
    	return $posts;
  3. archon810
    Posted 6 years ago #

    Verified as working! This is a step up from the level I was thinking at, but it works, both on single and multiple post pages (if that wasn't obvious).

    Nice thinking.

  4. redwallhp
    Posted 6 years ago #

    Code looks good, shadow.

    I think that it would make a nice plugin. A simple admin page where you can specify a keyword in the content, and bind a style/script to it.

  5. FractalizeR
    Posted 6 years ago #

    Very nice solution indeed. Incorporating into my WP-SynHighlight plugin now.

  6. archon810
    Posted 6 years ago #

    @redwallhp, I see more use the other way around - from within existing plugins that would otherwise load their crap all over the place.

  7. PhillKenoyer
    Posted 6 years ago #

    Anything new in WordPress 3 to help with this issue?

  8. islandcastaway
    Posted 5 years ago #

    I'm trying to get this technique to work with the Audio-player plugin( http://wordpress.org/extend/plugins/audio-player/ ).

    It uses addHeaderCode() and addFooterCode() too insert.

    Could someone point me in the right direction please?

Topic Closed

This topic has been closed to new replies.

About this Topic