我创建一个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中显示?
答案 0 :(得分:2)
$visitor
。我猜这会奏效:
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' );