I am hoping someone may be able to help me with a problem. I am building a news web site for a friend of mine. The site is starting to come together, but I cannot find out how to add captions to featured images. I have been looking all over the web today, there are loads of ways to do it by adding code to php sheets, but I am not sure what I am doing.
I have added so code to the functions.php code, but the everything goes pair shaped.
I am keeping my fingers crossed, someone will be able to help me by typing me through what to do.
Thank you in advance for your help.
Kind regards
John
First, you'll need to drop the following code in your functions.php file:
function the_post_thumbnail_caption() {
global $post;
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[0])) {
echo '<span>'.$thumbnail_image[0]->post_excerpt.'</span>';
}
}
Paste it right before the closing PHP tag in that file, if there isn't a closing PHP tag then make sure there's no empty lines below the code you paste as that can cause problems.
Then, where you'd like the caption to be displayed, you'll need to call it with this:
<?php the_post_thumbnail_caption(); ?>
If you're unsure where to put the call in your template files, you'll need to find where <?php the_post_thumbnail(); ?>
is being called. Just look for that line in your template file, and place the function call near it, where ever you'd like the caption to be displayed at. The function wraps the caption in a span tag automatically so you can target it with CSS, but you can also wrap the function call in any tag you'd like to.
So for example, if your template file is calling the featured image with this or something very similiar:
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
} ?>
You'd want to add the caption call to it like this:
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
} ?>
<?php the_post_thumbnail_caption(); ?>
Let me know if you need any other clarification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With