1

I add captions to images in WordPress using the "Caption" box to indicate the photographer's name.

I need custom text to always be displayed before the image caption,

That is, now I just have “text”, but I need it to become like this: “Photo: text”. This must be done for all image captions in WP posts.

The caption code for the images in the article now looks like this:

<p id="caption-attachment-00001 class="wp-caption-text">Image caption</p>

How can i do this? enter image description here

1 Answer 1

1

You can filter the image caption using the wp_get_attachment_caption filter:

add_filter( 'wp_get_attachment_caption', 'wpse422651_filter_image_caption', 10, 2 );

/**
 * Filters the image caption.
 *
 * @param  string $caption       The image caption.
 * @param  int    $attachment_id The attachment ID.
 * @return string                The filtered caption.
 */
function wpse422651_filter_image_caption( $caption, $attachment_id ) {
  // Only run if the caption isn't empty and the attachment is an image.
  if ( ! empty( $caption ) && wp_attachment_is_image( $attachment_id ) ) {
    return 'Photo: ' . $caption;
  }
}

References

3
  • Thank you! But unfortunately this doesn't work for me ((( I don't notice any changes to the image captions in the posts. Of course I cleared the cache.
    – Jusper
    Commented Feb 21 at 3:03
  • Your code worked for thumbnails (featured post image). I display them using the code <?php the_post_thumbnail_caption(); ?> But your code does not affect the images that are inside the post content.
    – Jusper
    Commented Feb 21 at 3:08
  • Sounds like I've got the wrong filter here. I'll see what I can find a little later.
    – Pat J
    Commented Feb 21 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.