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

Leave a Reply

Your email address will not be published. Required fields are marked *

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