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:
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:
You’d want to add the caption call to it like this:
Let me know if you need any other clarification.
I know this is an old question, but I wanted to offer another solution that others might prefer, if you would rather deal with data that is already available (less database calls) while using fields already available in WordPress.
Since the output of
get_the_post_thumbnail()
returns the entire img tag as a string with the alt tag pre-populated from the caption field, you can simply extract the alt tag of the image tag by using xml parser or regex.I did this:
If you want it in a function like the originally accepted answer, you pass the img tag directly to your function:
And in the template:
Note that if you populate the ‘alt text’ field, it will overwrite the caption field data when outputting the img tag. You can override that behavior with filters if necessary.