admin管理员组

文章数量:1134247

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>

Becomes:

<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.

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>

Becomes:

<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.

Share Improve this question asked Sep 24, 2023 at 20:03 Terence EdenTerence Eden 1577 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

Notes

  • 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.

References

  • the_content
  • is_single()
  • preg_replace()

本文标签: filtersReplace image with its alt text