我正在创建一个返回一堆HTML元素的短代码。一开始就可以这样做:
add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
return "<div>Some content here.</div>";
}
但是现在我必须添加很多内容,我认为这些内容看起来不太好,因为我的functions.php
将充满了很多内容。我想知道我是否可以把它放在外部文件中并包含它。
我希望这样的事情会起作用:
add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
return include 'about-us.php';
}
但当然,事实并非如此。有关如何正确做到这一点的任何想法?感谢
答案 0 :(得分:0)
尝试以下代码:
add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about()
{
ob_start();
require_once('about-us.php');
$data = ob_get_contents();
ob_end_clean();
return $data;
}
在about-us.php中的代码
<div>Some content here.</div>
答案 1 :(得分:0)
add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about()
{
// Get absolute path to file.
$file = locate_template('my-file.php');
// Check if file is found.
if ($file) {
// Return file contents.
ob_start();
include $file;
return ob_get_clean();
}
return '';
}
答案 2 :(得分:-1)
使用此
add_shortcode( 'about_us', 'shortcode_about' );
function add_shortcode()
{
ob_start();
include( dirname ( __FILE__ ) . '/include.php' );
return ob_get_clean();
}
和 include.php
<h1>Test Content</h1>
<p>This is the data</p>