2013-10-28 28 views
1

我有一個包含多個簡碼的頁面。我希望每個簡碼的內容都包含HTML標籤。我有下面的代碼幾乎可以工作,但它包裹了一個div中的所有短代碼。用do_shortcode()圍繞每個簡碼包裝HTML

<?php $sidebarBlocks = get_post_meta($post->ID, "page_sidebarhubspot", true); ?> 
<?php echo do_shortcode('<div>'.$sidebarBlocks.'</div>'); ?> 

此輸出..

<div> 
    <p>Content from shortcode1</p> 
    <p>Content from shortcode2</p> 
    <p>Content from shortcode3</p> 
</div> 

我想這是什麼..

<div> 
    <p>Content from shortcode1</p> 
</div> 

<div> 
    <p>Content from shortcode2</p> 
</div> 

<div> 
    <p>Content from shortcode3</p> 
</div> 

我怎樣才能做到這一點?謝謝!

回答

0

你可以嘗試這樣的[可以刪除htmlentities()我已經用它用於說明目的,只使用純echo]

<?php $sidebarBlocks = get_post_meta($post->ID, "page_sidebarhubspot", true); ?> 
<?php 
$sidebarBlocks=str_replace("<p>","<div><p>",$sidebarBlocks); 
$sidebarBlocks=str_replace("</p>","</p></div>",$sidebarBlocks); 
echo htmlentities($str); 
?> 

OUTPUT:

<div><p>Content from shortcode1</p></div> 
<div><p>Content from shortcode2</p></div> 
<div><p>Content from shortcode3</p></div> 
2

這是一個很好的問題 - 我認爲目前沒有黑客入侵的可能性。這裏是我再去想了:

<?php 
function my_override_shortcodes() { 
    global $shortcode_tags, $_shortcode_tags; 

    // Let's make a back-up of the shortcodes 
    $_shortcode_tags = $shortcode_tags; 

    // Add any shortcode tags that we shouldn't touch here 
    $disabled_tags = array('gallery'); 

    foreach ($shortcode_tags as $tag => $cb) { 
     if (in_array($tag, $disabled_tags)) { 
      continue; 
     } 
     // Overwrite the callback function 
     $shortcode_tags[ $tag ] = 'my_wrap_shortcode_in_div'; 
    } 
} 
add_action('init', 'my_override_shortcodes', 9999); 

// Wrap the output of a shortcode in a div with class "i-wrap-you" 
// The original callback is called from the $_shortcode_tags array 
function my_wrap_shortcode_in_div($attr, $content = null, $tag) { 
    global $_shortcode_tags; 
    return '<div class="i-wrap-you">' . call_user_func($_shortcode_tags[ $tag ], $attr, $content, $tag) . '</div>'; 
} 

所以這裏所發生的是,在init我們複製所有的註冊簡碼,並與我們自己的功能覆蓋其回調函數。

當被調用時,在另一隻手上的函數返回一個打開的div標籤,隨後是原始回調函數的輸出,然後是一個閉合的div標籤。

如果你想覆蓋的簡只爲do_shortcode電話,你可以做這樣的事情:

function my_restore_shortcodes() { 
    global $shortcode_tags, $_shortcode_tags; 

    // Restore the original callbacks 
    if (isset($_shortcode_tags)) { 
     $shortcode_tags = $_shortcode_tags; 
    } 
} 

並在代碼中做到這一點:

$sidebarBlocks = get_post_meta($post->ID, "page_sidebarhubspot", true); 

my_override_shortcodes(); 

echo do_shortcode('<div>'.$sidebarBlocks.'</div>'); 

my_restore_shortcodes(); 

當然,如果你使用第二種方法,別忘了刪除該行

add_action('init', 'my_override_shortcodes', 10); 

作爲my_override_shortcodes()函數可以指定不會覆蓋的簡碼($disabled_tags數組)。