WordPress:将 `get_template_part()` 保存到变量
简而言之,我需要的只是让我的 WordPress 执行此操作
$var = get_template_part( 'loop', 'index' );
,但是 get_template_part()
不会返回 HTML,而是打印它。
我需要将此 HTML 存储在 $var
中 - 你有什么想法如何做到这一点吗?
In short, all I need is to make my WordPress do this
$var = get_template_part( 'loop', 'index' );
but, get_template_part()
does not return HTML, it prints it.
I need this HTML stored in $var
- do you have any ideas how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这不是
get_template_part
的用途,get_template_part 本质上的行为类似于 PHP 的 require 函数。 Justin Tadlock 在这里写了很多相关内容 和还讨论了一个可能对您更有用的 WordPress 函数 -locate_template
。或者,如果您确实想使用 get_template_part 破解此功能,则可以使用模板缓冲:
This isn't what
get_template_part
was for, get_template_part essentially behaves like PHP's require function. Justin Tadlock writes a lot more about this here and also talks about a Wordpress function that might be more useful to you -locate_template
.Alternatively, if you did want to hack this functionality using get_template_part, you could use template buffering:
我不喜欢输出缓冲,尽管+1甚至认为这是一个选项!
我认为 Helga 的观点是正确的,但您仍然需要尊重 child_themes 和主题路径,因此请使用
locate_template()
(也如 Simon 建议的那样)。这工作得很好,甚至可以在过滤器或(在我的例子中)短代码函数中使用(我希望我的短代码在模板样式文件中输出内容,以将显示层与逻辑层分开)。
I'm not loving Output Buffering, though +1 for even thinking of that as an option!
I think Helga was on to something, but you need to still respect the child_themes and the theme path, so use
locate_template()
instead (also as Simon suggested).This works nicely, and can even be used inside a filter or (in my case) shortcode function (I wanted my shortcode to output the content within a template-style file, to separate the display layer from the logic layer).
又怎么样?
我确信有更好的方法,但这似乎对我有用。
what about?
i'm sure there is a better way, but that seems to work for me.
如果您的目标是创建带有 HTML 返回的短代码,那么下面的示例适合我:
If your goal is to create a shortcode with the HTML return, the example below works for me:
这对我有用
This worked for me
我知道我迟到了,但我所做的不需要输出缓冲的只是将其放入函数中,将函数保存在functions.php中,并将其返回的内容保存到变量中。
I know I'm late to the party, but what I do that doesn't require output buffering is to just put it in a function, save function in functions.php, and save what it returns to a variable.