• leon1025

    (@leon1025)


    l want to loop the post,if there is a feature image(or called thumbnail images) in post,loop the thumbnail,if not,loop the first images in content;here is my code added in functions.php

    function don_the_thumbnail() {
        global $post;
        $thumbnail = get_post( get_post_thumbnail_id() );
        if ( has_post_thumbnail() ) { //judge whether there is a thumbnail in the post
            echo '<a href="'.get_the_permalink().'"><img class="img-responsive img-blog" src="'.get_the_post_thumbnail_url().'" alt="'.get_post_meta( $thumbnail->ID, '_wp_attachment_image_alt', true ).'" /></a>';
        } else { //if not,get find whether there is an image in post
            $content = $post->post_content;
            preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
            $n = count($strResult[1]);
            if($n > 0){ // if there is an image in post,get the first image
                echo '<a href="'.get_the_permalink().'"><img class="img-responsive img-blog" src="'.$strResult[1][0].'" alt="" /></a>';
            }else { // if there is no image in post,nothing get
                return;
            }
        }
    }

    the problem is that how do l get the alt text of the first image in the post?need a hand,thank you all.

  • The topic ‘how to get alt of image’ is closed to new replies.