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.
1 Answer
Reset to default 1You 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
版权声明:本文标题:filters - Replace image with its alt text? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736792822a1953163.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论