2015-10-20 113 views
2

我正在創建一個名爲woomps的插件。在主要的php文件中,我在模板重定向時做了一個計算。調用變量正確並顯示PHP生成的HTML in_content()

add_action('template_redirect','woomps_loop'); 

這個計算x :(這實際上是一個很大的計算)。

function woomps_loop() { 
$x = 10; 
Return $x 
} 

我想根據簡碼顯示這個變量。因此,在我的主要PHP文件中,我通過這個代碼包含了frontend.php。

function woomps_scripts() { 
    include 'frontend.php'; 
} 
    add_action('wp_enqueue_scripts','woomps_scripts'); 

凡frontend.php有這個代碼

function woomps_subscription_slider(){ 
    //How do I call the variable from woomps_loop() without running all the code again. 
    echo "<div>\n"; 
    echo "<p>\n"; 
    echo $x; 
    echo "</p>\n"; 
    echo "</div>\n"; 
} 
add_shortcode("woomps-subscription-slider", "woomps_subscription_slider"); 

短碼被添加到我的網頁,使其顯示一個,但是......


  1. 怎麼辦我打電話$x變量形式woomps_loop()而無需再次運行代碼?
  2. <div>將在the_content()中生成的所有其他內容之前出現。這是爲什麼?

回答

1
global $x; //Had to define it global before setting it, i dident understand this before @cameronjonesweb exmample. 
$x = $total_qty; 

然後像這樣引用它:

function woomps_subscription_slider ($x){ 
global $x_subs; 
$content = <<<EOD 
<div> 
<p> 
{$x_subs} 
</p> 
</div> 
EOD; 

return $content; 
} //end woomps_subscription_slider 

它的工作。嘗試這種EODreturn HTML的多行,並且它的放入內部the_content()

  • 好。謝謝!
  • +0

    將$ x_subs轉換爲$ x。也許我肩膀回答我自己的問題:|新的到stackoverflow。 – robped

    0

    1)將其存儲爲全局變量。因此,改變你的woomps_loop功能

    global $x; 
    
    function woomps_loop() { 
        global $x; 
        $x = 10; 
        return $x 
    } 
    

    (PS你可能不會需要回到這裏$x現在) 然後在您的簡碼的功能還定義$x

    function woomps_subscription_slider(){ 
        global $x; 
        echo "<div>\n"; 
        //... rest of it carries on 
    

    2)因爲你是echo ING。改爲返回值。