Gar*_*rom 9 php wordpress shortcode
我有一个页面,我需要允许用户输入一段文字.然后在该文本之后插入一个将呈现帖子列表的短代码,然后添加更多自由格式文本.我的想法是他们应该能够插入一个输出帖子的短代码.这样他们就可以简单地在他们希望帖子出现的地方添加短代码.
我目前有逻辑检索在自己的文件中分隔的帖子.目前我只需使用以下get_template_part()功能将其包含在页面中:
get_template_part('donation', 'posts');
Run Code Online (Sandbox Code Playgroud)
我研究了如何创建一个短代码,并在我的functions.php文件中包含以下代码以创建短代码:
add_shortcode('donation-posts', 'fnDonatePosts');
function fnDonatePosts($attr, $content)
{
get_template_part('donation', 'posts');
}
Run Code Online (Sandbox Code Playgroud)
在donation-posts.php该短码被放置的位置被正确执行和职位出现,但是,他们总是定位在内容之前不能及的.
我已经尝试删除该get_template_part()功能,只输出一些文本,并且工作正常.所以我明白这get_template_part()可能不是正确的方法,但是,我还没有找到办法去做我想做的事情(我确信有办法...我只是避风港'找到它).
我试过了:
include(get_template_directory(). '/donation-posts.php');
include_once(get_template_directory(). '/donation-posts.php') :
Run Code Online (Sandbox Code Playgroud)
但是一旦他们点击了包含文件中的PHP代码,这些就停止了处理.
我也尝试过:
$file = file_get_contents(get_template_directory(). '/donation-posts.php');
return $file;
Run Code Online (Sandbox Code Playgroud)
但这只返回文件的内容(如函数名所示),这意味着它不会执行 PHP脚本来返回帖子.
以前有人这样做过吗?
The*_*pha 18
你可以尝试这个,它可以解决你的问题,因为get_template_part基本上会做出反应PHP's require,它不会返回,但会立即回复调用它的内容.
add_shortcode('donation-posts', 'fnDonatePosts');
function fnDonatePosts($attr, $content)
{
ob_start();
get_template_part('donation', 'posts');
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
Run Code Online (Sandbox Code Playgroud)
这是一个更动态的版本,您可以将路径传递给模板.
function template_part( $atts, $content = null ){
$tp_atts = shortcode_atts(array(
'path' => null,
), $atts);
ob_start();
get_template_part($tp_atts['path']);
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
add_shortcode('template_part', 'template_part');
Run Code Online (Sandbox Code Playgroud)
和短代码:
[template_part path="includes/social-sharing"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9542 次 |
| 最近记录: |