Wordpress - Insert Custom HTML After Shortcode
I wonder if you could override the [rev_slider]
with this kind of wrapper:
add_shortcode( 'rev_slider', function( $atts = array(), $content = '' )
{
$html = '';
// Your custom banner HTML
$banner = '<div id="bannerHTML"><!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
if( function_exists( 'rev_slider_shortcode' ) )
$html = rev_slider_shortcode( $atts, $content ) . $banner;
return $html;
} );
Where we assume that the original shortcode's callback is rev_slider_shortcode()
. We have to run the after the original one.
Update
As suggested by @Sumit we could try to get the shortcode's callback from the $shortcode_tags
array.
Here's an example:
add_action( 'after_setup_theme', function() use ( &$shortcode_tags )
{
// Shortcode to override. Edit to your needs
$shortcode = 'rev_slider';
// Nothing to do if it's not registered as shortcode
if( ! shortcode_exists( $shortcode ) )
return;
// Get the shortcode's callback
$callback = $shortcode_tags[$shortcode];
// Override the shortcode
add_shortcode( $shortcode, function( $atts = array(), $content = '' ) use ( $callback )
{
// Your custom banner HTML
$banner = '<div id="bannerHTML">123<!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
return
is_callable( $callback )
? call_user_func( $callback, $atts, $content, $callback ) . $banner
: '';
} );
}, PHP_INT_MAX );
Here we hook late into the after_setup_theme
action and use call_user_func()
to run the previous shortcode's callback, similar how it's done in do_shortcode_tag()
.
This is a solution I've come up with after refining it a bit. The below should only run if the shortcode exists in the content. It loops through all the shortcodes to find the specific one we need, replaces it with the shortcode plus the new HTML:
function insert_after_shortcode( $content ) {
if( ! has_shortcode( $content, 'shortcode_name' ) ) {
return $content;
}
ob_start();
?>
<div id="bannerHTML"><!-- banner HTML goes here --></div>
<?php
$additional_html = ob_get_clean();
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'shortcode_name' === $shortcode[2] ) {
$new_content = $shortcode[0] . $additional_html;
$content = str_replace( $shortcode[0], $new_content, $content );
}
}
}
return $content;
}
add_filter( 'the_content', 'insert_after_shortcode' );