No, by the time your shortcode runs, the header has already been sent over the network, even the post title. It is too late to change things already sent, aka everything before it reached the_content
.
There is 1 way to "do it" sort of, but it carries a very, very high cost, and won't be reliable. Start an output buffer at the beginning of every page, then process the page at the end. However, this will:
- Utterly cripple the TTFB/time to first byte, making your pages slow, and eliminating all progressive rendering at the client end, and parallelisation on the network side. This will probably have SEO ranking consequences
- Require a
shutdown
hook, if this is never reached then nothing will be shown on the page, the user will see a completely blank page with no markup at all
- Introduces overhead of string parsing HTML, which can get messy
- It will require a supporting infrastructure to register all the stuff you want to add, otherwise if you try to flush the output buffers in the shortcode you won't have any way to use the shortcode a second time
- Most of what you want to add will get stripped out by WordPress for not passing
wp_kses_post
on save. Fixing this will mean opening up major security holes
Fundamentally, this is not the approach to take to solve these problems
Instead, if you want to add JSON-LD to the header, you should use PHP code to add it on the wp_head
hook, or if possible in the footer or further down the page. You shouldn't rely on shortcodes for anything other than embedding things into post content that can't be put directly into post content, e.g. iframes or fancy javascript features like interactive graphs