• 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).

    Thanks,
    Artem
    http://beerpla.net

Viewing 7 replies - 1 through 7 (of 7 total)
  • 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;
    			break;
    		}
    	}
    
    	if ( $shortcode_found ){
    		wp_enqueue_style('my-style');
    		wp_enqueue_script('my-script');
    	}
    
    	return $posts;
    }
    Thread Starter archon810

    (@archon810)

    @white_shadow
    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.

    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.

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

    Thread Starter archon810

    (@archon810)

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

    Anything new in WordPress 3 to help with this issue?

    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?

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Enqueue and load a CSS file *only* if string in content matches?’ is closed to new replies.