php Wordpress:使用函数 get_post_field() 获取帖子内容时,短代码不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22270147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wordpress: shortcode doesn't work when getting post content using function get_post_field()
提问by user3396122
I want to get the post content by id outside the loop, so i am using following code:
我想通过循环外的 id 获取帖子内容,所以我使用以下代码:
echo get_post_field('post_content', $postid);
It works fine, however, if the post contains any shortcodes, the shortcodes don't work properly. It only echoes the shortcode as plain text.
它工作正常,但是,如果帖子包含任何短代码,则短代码将无法正常工作。它仅以纯文本形式回显短代码。
Example: I'm using following code in editor to display image and caption text inder the image:
示例:我在编辑器中使用以下代码在图像中显示图像和标题文本:
[caption id="attachment_23" align="alignnone" width="300"]<img class="size-medium wp-image-23 " alt="" src="http://localhost/wordpress/wp-content/uploads/2014/03/Desert-300x225.jpg" width="300" height="225" /> this is caption[/caption]
But when i get this post content using function get_post_field(), Instead of displaying caption text, it displays:
但是,当我使用 function 获取此帖子内容时get_post_field(),它不会显示标题文本,而是显示:
[caption id="attachment_23" align="alignnone" width="300"]this is caption[/caption]
Any solution?
有什么解决办法吗?
N.B: I am using ajax to get the contents
注意:我正在使用 ajax 来获取内容
回答by Rahil Wazir
This will work:
这将起作用:
echo do_shortcode(get_post_field('post_content', $postid));
Edit
编辑
If you want to forcefully output shortcode within Ajax, please see running shortcode inside AJAX request
如果您想在 Ajax 中强制输出短代码,请参阅在 AJAX 请求中运行短代码
回答by andreivictor
You need to filter your content before displaying it, so try the following code:
您需要在显示内容之前对其进行过滤,因此请尝试以下代码:
echo apply_filters( 'the_content', get_post_field('post_content', $postid) );
Update:You can't output shortcodes using ajax calls hooked into wp_ajax.
WP Ajaxruns both public as well as closed calls via admin.php. This means that you don't have access to the whole wp environment, such as do_shortcode(), which is inside /wp-includes/shortcodes.php.
更新:您不能使用挂钩到wp_ajax.
WP Ajax通过admin.php. 这意味着,你不必访问整个WP的环境,比如do_shortcode(),这是里面/wp-includes/shortcodes.php。
回答by Rashmi Narware
This works for me.
这对我有用。
echo apply_filters( 'the_content', get_post_field('post_content', $postid) );
echo apply_filters('the_content', get_post_field('post_content', $postid));
As I am doing it outside the loop.
正如我在循环之外做的那样。

