Anonymous function is executed twice in wp_head while added from the_posts filter?

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?

1 Answer
1

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' );

Leave a Comment