2015-10-14 51 views
3

我想寫一個短代碼嵌套在其中的另一個短代碼。 [map id =「1」] shortcode是從一個不同的插件生成的,但我想在執行這個簡碼時顯示地圖。爲wordpress輸出回聲內的短代碼

我不認爲這是最好的方式去做這件事,但我仍然是新的PHP編碼。

<?php 
add_shortcode('single-location-info', 'single_location_info_shortcode'); 
    function single_location_info_shortcode(){ 
     return '<div class="single-location-info"> 
        <div class="one-half first"> 
         <h3>Header</h3> 
         <p>Copy..............</p> 
        </div> 
        <div class="one-half"> 
         <h3>Header 2</h3> 
         <p>Copy 2............</p> 
         <?php do_shortcode('[map id="1"]'); ?> 
        </div> 
       </div>'; 
       } 
?> 

我不認爲我應該嘗試從迴歸中調用PHP ....我雖然我讀的地方,我應該使用「定界符」,但我一直無法得到它的正常工作。

任何雖然?

謝謝

回答

2

你的直覺是對的。不要在中間返回帶有php功能的字符串。 (不太可讀,上面的示例代碼將不起作用)

heredoc不會解決此問題。雖然有用,但heredocs真的只是在PHP中構建字符串的另一種方式。

有幾個潛在的解決方案。

的 「PHP」 解決方案是使用輸出緩衝:

ob_start
ob_get_clean

,這裏是你修改後的代碼,會做你的要求:

function single_location_info_shortcode($atts){ 
    // First, start the output buffer 
    ob_start(); 

    // Then, run the shortcode 
    do_shortcode('[map id="1"]'); 
    // Next, get the contents of the shortcode into a variable 
    $map = ob_get_clean(); 

    // Lastly, put the contents of the map shortcode into this shortcode 
    return '<div class="single-location-info"> 
       <div class="one-half first"> 
        <h3>Header</h3> 
        <p>Copy..............</p> 
       </div> 
       <div class="one-half"> 
        <h3>Header 2</h3> 
        <p>Copy 2............</p> 
        ' . $map . ' 
       </div> 
      </div>'; 
    } 

備用方法

這樣做將是嵌入在內容串短碼,並通過WordPress的the_content filter功能運行的「WordPress的路」:

function single_location_info_shortcode($atts) { 
    // By passing through the 'the_content' filter, the shortcode is actually parsed by WordPress 
    return apply_filters('the_content' , '<div class="single-location-info"> 
       <div class="one-half first"> 
        <h3>Header</h3> 
        <p>Copy..............</p> 
       </div> 
       <div class="one-half"> 
        <h3>Header 2</h3> 
        <p>Copy 2............</p> 
        [map id="1"] 
       </div> 
      </div>'); 
    } 
+0

你的WordPress的解決方案完美地工作!謝謝!!!! – William