LoginSign Up

Get the first image in a post in wordpress

প্রোগ্রামিং 1 year ago 26 Jul, 2019 at 3:03 pm 230
Linkedin Pint
Get the first image in a post in wordpress

/**
 * Get the first image in a post. Strip Version. Retrieve the first image from each post and resize.
 *
 * @param string $size get the first image size.
 * @link https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
 * see
 * Usage: Include in functions.php
 * <?php echo get_first_image('thumbnail'); ?> in the page template.
 */
function get_first_image( $size = 'thumbnail' ) {
    global $post, $posts;
    $first_img = '';
    preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', do_shortcode( $post->post_content, 'gallery' ), $matches );
      $first_img = isset( $matches[1][0] ) ? $matches[1][0] : null;

    if ( empty( $first_img ) ) {
            return get_template_directory_uri() . '/assets/images/empty.png'; // path to default image.
    }

    // Now we have the $first_img but we want the thumbnail of that image.
     $explode = explode( '.', $first_img );
     $count = count( $explode );
     $size = '-624x312'; // Our panel ratio (2:1) 312x156 for lighther page, 624x312 for retina; use add_image_size() and Force Regenerate Thumbnails plugin when changing sizes.
     $explode[ $count -2 ] = $explode[ $count -2 ] . '' . $size;
     $thumb_img = implode( '.', $explode );
     return $thumb_img;
}
    add_filter( 'get_first_image', 'thumbnail' ); gist
1 year ago

Abdullah sk
I,m article writer, part time job in kokilbd
Like - Dislike Votes 0 - Rating 0 of 10

Be the first to comment

Leave a Reply

Your email address will not be published.


*


Enter Captcha Here : *

Reload Image

     

আরও দেখুন

ফোরাম বিভাগ