Website Development

How To Keep Image Caption Shortcodes from Appearing in WordPress

WordPress LogoSometimes when content is fetched within WordPress formatting is not maintained correctly. For instance, caption shortcodes might not be parsed as they should and the shortcodes will appear in the body of posts, pages, etc.

Part 1 of this tutorial covers how to create a custom call for fetching post content while maintaining formatting (i.e. parsing image shortcodes) by placing some code in your custom_functions.php file.

Part 2 of this tutorial describes how to combine the custom call with our post about showing blog posts on a static homepage with the Thesis theme for WordPress to

Part 1:
First you need to create a custom call for fetching post content that maintains formatting (captions were showing previously because the content was getting fetched without formatting).

<?php echo get_the_content(); ?>

returns content without formatting.

<?php the_content(); ?>

will return content with formatting

A) For the example, we will call the new function get_the_content_with_captions.

B) First, define parameters for the get_the_content_with_captions function. For the example, we will use “more…” for the link text, 0 for teaser length before the more text, and null for more file. The code now looks like

function get_the_content_with_captions ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);

C) Now add two lines below to parse shortcodes:

$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);

D) And one line to output content:

return $content;

E) The final version of the custom call should look like the code below, paste it into the bottom of your custom_functions.php file.

/*Add custom function to include captions on recent post--home*/
function get_the_content_with_captions ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}

Part 2:
Now you need to update the code for displaying recent posts on a static homepage with the new custom call. The code (and directions for configuring it before you modify it to preserve formatting) is available in one of our previous posts.

A) Find the get_the_content / get_the_except call around line 12 of the code.

B) Change it to get_the_content_with_captions and save custom_functions.php

The homepage will now display recent posts with formatting, such as captions, preserved.

2 Comment on “How To Keep Image Caption Shortcodes from Appearing in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *