Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I know this sounds complicated, so bear with me.

I'm trying to add certain custom css styles based on the shortcodes(if any) in the current post/page.

function load_shortcode_styles($posts){

      //function to check short codes here

      //regex to get id from shortcode(e.g [item id=""] )

      //get custom post meta from the id that has my custom css

      add_action('wp_head', create_function('', 'echo "\n<!-- my style -->\n<style>' . $custom_css . '</style>\n";') );

}

add_filter('the_posts', 'load_shortcode_styles' );

After I open my post pages, the source shows my style being printed twice like:

<!-- my style -->
<style>
</style>
<!-- my style -->
<style>
</style>

For testing purposes I used a hardcoded function to echo a certain string, and it works fine.

e.g. :

function test_print(){
    echo "\n<!-- my style -->\n<style>foo bar</style>\n";
}

and replace above action hook with this

add_action('wp_head', 'test_print' );

Somehow, this will print, which is the correct one!

<!-- my style -->
<style>
foo bar
</style>

Does anyone know about this issue? How can I solve this?

share|improve this question
    
If without anonymous function it works fine don't use them, also it would be hard for user to remove anonymous function attached to action, if they don't want to print those styles –  Mamaduka Nov 14 '11 at 7:52

1 Answer 1

up vote 1 down vote accepted

I can only assume that on the page there are either multiple queries or instances of this post, but eitherway it exposes a flaw in the logic, that you're not checking if the style has already been added. Normally one would use wp_enqueue_script which would sort this out, but for whatever reason you may not be able to do that.

So, instead, you need to do that check first. I would reccomend the following:

global $we_found_shortcode; $we_found_shortcode = false;

function load_shortcode_styles($posts){

      //function to check short codes here

      // if found

      $we_found_shortcode = true;
}

function header_check(){
    global $we_found_shortcode;
    if($we_found_shortcode == true){
        //regex to get id from shortcode(e.g [item id=""] )

        //get custom post meta from the id that has my custom css

        echo "\n<!-- my style -->\n<style>' . $custom_css . '</style>\n";
    }

}

add_filter('the_posts', 'load_shortcode_styles' );
add_filter('wp_head', 'header_check' );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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