WordPress 短碼後插入自定義 HTML
問題描述
這種情況是我需要在主頁內容中的一個短碼的幻燈片中添加一個 HTML 橫幅。我個人不喜歡在 TinyMCE 編輯器中添加一堆 div 標籤,所以我試圖過濾 the_content,並在特定的短代碼之後添加我的 HTML 。以下是一個解決方案,但我不知道是否有更好的方法來解決這個問題。
在特定短信之後添加內容的最佳方式是什麼?
最佳解決方案
我想知道你是否可以使用這種封裝來覆蓋 [rev_slider]:
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;
} );
我們假設原始短碼的回調是 rev_slider_shortcode()。我們必須運行原來的。
Update
根據 @Sumit 的建議,我們可以嘗試從 $shortcode_tags 數組獲取短代碼的回調。
以下是一個例子:
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 );
這裏我們將 after_setup_theme 動作拖到 after_setup_theme 動作中,並使用 call_user_func()來運行以前的短代碼回調,與 do_shortcode_tag()相似。
次佳解決方案
這是一個解決方案,我已經提出了一點點。只有當內容中存在短碼時,才應運行以下內容。它循環遍歷所有的快捷碼,找到我們需要的特定的代碼,用短碼替代新的 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' );
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。