最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

filters - How to get title of images in post content

programmeradmin1浏览0评论

Today I have the function created below using regex that inserts the POST title if the ALT attribute of the image inserted in the content is empty.

But now I want to get the title of the image and not the post. How to make?

if( ! ( function_exists( 'add_alt_image_content' ) ) ) {
    function add_alt_image_content( $content ) {

        if ( is_single() && in_the_loop() && is_main_query() ) {

            global $post;

            $image = get_post( $post->ID );
            $image_title = $image->post_title;
    
            $pattern = '~(<img.*? alt=")("[^>]*>)~i';
            $replace = '$1'.$image_title.'$2';
            $content = preg_replace( $pattern, $replace, $content );
            
            return $content;
        }
    } 
}
add_filter( 'the_content', 'add_alt_image_content' );

Today I have the function created below using regex that inserts the POST title if the ALT attribute of the image inserted in the content is empty.

But now I want to get the title of the image and not the post. How to make?

if( ! ( function_exists( 'add_alt_image_content' ) ) ) {
    function add_alt_image_content( $content ) {

        if ( is_single() && in_the_loop() && is_main_query() ) {

            global $post;

            $image = get_post( $post->ID );
            $image_title = $image->post_title;
    
            $pattern = '~(<img.*? alt=")("[^>]*>)~i';
            $replace = '$1'.$image_title.'$2';
            $content = preg_replace( $pattern, $replace, $content );
            
            return $content;
        }
    } 
}
add_filter( 'the_content', 'add_alt_image_content' );
Share Improve this question asked Nov 28, 2020 at 17:08 Renan BessaRenan Bessa 1316 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

just change the $post->ID with get_post_thumbnail_id(), and possibly we can delete also the global $post;

if( ! ( function_exists( 'add_alt_image_content' ) ) ) {
    function add_alt_image_content( $content ) {

        if ( is_single() && in_the_loop() && is_main_query() ) {

            global $post;

            $image = get_post(get_post_thumbnail_id());
            $image_title = $image->post_title;
    
            $pattern = '~(<img.*? alt=")("[^>]*>)~i';
            $replace = '$1'.$image_title.'$2';
            $content = preg_replace( $pattern, $replace, $content );
            
            return $content;
        }
    } 
}
add_filter( 'the_content', 'add_alt_image_content' );
发布评论

评论列表(0)

  1. 暂无评论