WordPress Hooks Insert Code After Body

WordPress Hooks Insert Code After Body

You could run hooks inside the body by adding manually an add_action below body tag, for example:

do_action('after_body');

But in some cases, if your building a shortcode based plugin and might need to make this automatically added right after the , the PHP output buffer and regular expression could be helpful on those instances, example:

// BUFFER START
function process_buffer_start() {
    ob_start();
}
add_action( 'wp_head', 'process_buffer_start');

function process_buffer_end() {

    $get_clean_buffer = ob_get_clean();
    ob_start();
    $process_shortcode = do_shortcode( '[myshortcode text="WordPress"]' );
    echo preg_replace( '<body.*>', '$0' . $process_shortcode, $get_clean_buffer );
    ob_flush();
}
add_action( 'wp_footer', 'process_buffer_end');

// SHORTCODE
function myshortcode_fallback( $atts ) {
    $a = shortcode_atts( array(
    'text' => ''
    ), $atts );

    return sprintf( '<div>I love %1$s</div>', $a['text'] );
}
add_shortcode( 'myshortcode', 'myshortcode_fallback' );


Stay in the loop with our web development newsletter - no spam, just juicy updates! Join us now. Join our web development newsletter to stay updated on the latest industry news, trends, and tips. No spam, just juicy updates delivered straight to your inbox. Don't miss out - sign up now!


We’ve tried our best to explain everything thoroughly, even though there’s so much information out there. If you found our writing helpful, we’d really appreciate it if you could buy us a coffee as a token of support.

Also, if you’re interested in learning more about WordPress, Javascript, HTML, CSS, and programming in general, you can subscribe to our MailChimp for some extra insights.

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.