15

I want to get the post content by id outside the loop, so i am using following code:

    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:

    [caption id="attachment_23" align="alignnone" width="300"]this is caption[/caption] 

Any solution?

N.B: I am using ajax to get the contents

user3396122
  • 153
  • 1
  • 1
  • 5

2 Answers2

24

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

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
  • This works, but i am trying to get the content using ajax request. in that case it doesn't work :( – user3396122 Mar 08 '14 at 16:19
  • 3
    @user3396122 You can't output shortcode using ajax. Because when doing ajax request the `admin-ajax.php` doesn't know about `shortcodes.php` file. You don't have access to whole wp environment when request with ajax. – Rahil Wazir Mar 08 '14 at 16:34
  • 1
    For future readers: If you want to forcefully output shortcode within Ajax, please [see](https://wordpress.org/support/topic/running-shortcode-inside-ajax-request?replies=9#post-5324569) – Rahil Wazir May 27 '16 at 08:09
17

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 Ajax runs 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.

andreivictor
  • 7,628
  • 3
  • 48
  • 75