从短代码函数内部调用WordPress get_template_part首先渲染模板

时间:2012-09-07 21:01:54

标签: php wordpress shortcode

我有一个页面,我需要允许用户输入一段文字。然后在该文本之后插入一个将呈现帖子列表的短代码,然后添加更多自由格式文本。我的想法是他们应该能够插入一个输出帖子的短代码。通过这种方式,他们可以简单地在他们希望帖子出现的地方添加短代码。

我目前拥有检索自己文件中分隔的帖子的逻辑。目前,我只需使用get_template_part()函数将其包含在页面中:

get_template_part('donation', 'posts');

我研究了如何创建一个短代码并将以下代码包含在我的functions.php文件中以创建短代码:

add_shortcode('donation-posts', 'fnDonatePosts');   
function fnDonatePosts($attr, $content)
{
    get_template_part('donation', 'posts');    
}

正在执行donation-posts.php并且帖子正在显示,但是,它们始终位于内容之前,而不是放置短代码的位置。

我尝试删除get_template_part()函数,只输出一些文本,效果很好。所以我理解get_template_part()可能不是正确的方法,但是,我还没有找到办法去做我想做的事情(我确信有办法......我只是没找到它。

我试过了:

include(get_template_directory(). '/donation-posts.php');
include_once(get_template_directory(). '/donation-posts.php') : 

但是一旦他们点击了包含文件中的PHP代码,这些就停止了处理。

我也尝试过:

$file = file_get_contents(get_template_directory(). '/donation-posts.php');  
        return $file;

但这只返回文件的内容(如函数名所示),这意味着它不会执行 PHP脚本来返回帖子。

以前有人这样做过吗?

4 个答案:

答案 0 :(得分: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;    
}

答案 1 :(得分:9)

这是一个更动态的版本,您可以将路径传递给模板。

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');  

短信码:

[template_part path="includes/social-sharing"]

答案 2 :(得分:1)

接受答案的最小版本:

function my_template_part_shortcode() {
    ob_start();
    get_template_part( 'my_template' );
    return ob_get_clean();
}
add_shortcode( 'my_template_part', 'my_template_part_shortcode' );

其中my-template.php是您要包含的文件。

答案 3 :(得分:1)

在functions.php中使用它时,

get_template_part()对我不起作用。我在ob_start中使用了locate_template()而是清理了。例如:

function full_petition_shortcode( $attr ) {
    ob_start();
    locate_template( 'petition.php', TRUE, TRUE );

    return ob_get_clean();
}
add_shortcode( 'full-petition', 'full_petition_shortcode' );
相关问题