I have a WordPress post with lots of inline HTML images.

I want to output my HTML in such a way that the existing:

<p>Here's my cat: <img src="example.jpg" alt="A photo of lovely black cat."></p>


<p>Here's my cat: A photo of lovely black cat.</p>

I know that I can use wp_kses($html, array( "img" => array( "alt"=>array() ) ) ); to preserve the <img> and alt. But I only want the alt.

Ideally, I'd like it to render as (Image. A photo of a lovely black cat.) - but I thought I'd see if there was a simple way of just getting the alt first.

1 Answer 1


You should be able to use the the_content filter for this. Something like this...

add_filter( 'the_content', 'wpse418925_replace_images_with_alt' );
function wpse418925_replace_images_with_alt( $content ) {
    // If you need to *only* do this on one post, check that we're in that post.
    // $desired_post can be an ID, post title, slug, or an array of any of those.
    if ( is_single( $desired_post ) ) {
        $content = preg_replace( '/<img.*(alt="[^"]+")[^>]*>/', '(Image. $1)', $content );
    return $content;

... might do what you're looking for.


  • This code is untested. Try it out on a local installation or a test site first.
  • This code is meant as a starting point only. In particular, it's likely you'll have to tweak the regular expression to suit your situation.
  • preg_replace() can be a "heavy" function, ie, time-intensive. You might want to consider caching the post's modified content to an option or to post_meta.


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.