1

how to store WP_head and footer functions in a variable? Is that possible?

I wanted to be like this.

$var = wp_head();

How can achieve it?

7
  • 3
    Mind if I ask why? Commented Jul 11, 2018 at 10:21
  • Sure it can be done, however, storing generated text this size in a variable may not be a good idea for performance. So it's better if you say why you need it for. Perhaps there's a better way to achieve what you want without storing wp_head() output in a variable.
    – Fayaz
    Commented Jul 11, 2018 at 11:18
  • @Fayaz Well, to be honest, wp_head isn’t so big comparing to rest of site... Storing it in a variable shouldn’t cause any (even small) performance problems at all... Commented Jul 11, 2018 at 11:30
  • @KrzysiekDróżdż I said may be. Also, I respectfully disagree on the possible performance issue. It's standard practice to output as soon as possible. When you optimize for close to 1000 concurrent views (even for 100 concurrency), "small" things like this add up 🙂
    – Fayaz
    Commented Jul 11, 2018 at 13:22
  • 1
    @Fayaz Of course it is a standard practice. But you've clearly stated, that "storing generated text this size in a variable may not be a good idea for performance" - and it's not true - size of wp_head is comparable or smaller than content and this, of course, is stored in a variable, so your comment doesn't make much sense... And even worse - it may be good for performance, if OP wants to put this string in transient and not generate it every time... Commented Jul 11, 2018 at 13:27

1 Answer 1

3

This function doesn't take any params, so there is no nice way of doing it.

But of course you can do this PHP way using output buffering ;)

ob_start();
wp_head();
$var = ob_get_clean();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.