簡體   English   中英

在函數中定義變量和回顯

[英]Define variable and echo in function

我正在創建一個WordPress插件,以從XenForo論壇中引入字段並將其顯示在WordPress中。

我有一個名為xf_connector.php的文件,其中包含以下代碼:

<?php

$startTime = microtime(true);
$fileDir = 'C:\Domains\xxxx.com\httpdocs\forums';

require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');

XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);

XenForo_Session::startPublicSession();

$visitor = XenForo_Visitor::getInstance()->toArray();
?>

然后是一個名為xf.php的單獨文件,其中包含以下代碼:

<body>
<p>Hello <?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?> welcome to this web page.</p>

<p>Hello <?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?> welcome to this web page.</p>

</body>

這在空白文檔中工作正常,但在WordPress插件中無效。 我的插件文件當前為:

include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
  ob_start(); ?> 
  <div class="xenfield">
<?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?>
  </div>
  <?php    return ob_get_clean();
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );

這不會在WordPress頁面上顯示任何內容,如果我查看HTML,它只會顯示空的<p>標記。

如何定義變量並在同一文件中回顯它以便在WordPress中顯示?

$visitor未在函數xenfield_shortcode()中定義。 我想這會起作用:

include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
  $visitor = XenForo_Visitor::getInstance()->toArray();

  ob_start(); ?> 
  <div class="xenfield">
<?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?>
  </div>
  <?php    return ob_get_clean();
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );

而當我們使用它時,這使它更具可讀性:

include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
    $visitor = XenForo_Visitor::getInstance()->toArray();

    $output = '<div class="xenfield">';
    $output .= $visitor['username'];
    $output .= '</div>';

    return $output;
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM