Search code examples
phpwordpressblogs

Image in every post in WordPress


If you visit this site, you will see that there is an image and summary for each post. What is the proper way to implement that?

Is this done using WordPress custom fields? Or whether this is coded in image.php file present in theme folder? How do I do that?


Solution

  • There is a better way - you can also use this function too -

    function catch_that_image() {
        global $post, $posts;
            $first_img = '';
            ob_start();
            ob_end_clean();
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
            $first_img = preg_replace("/_thumb[0-9]\./", "$1.", $first_img);
    
        // no image found display default image instead
            if(empty($first_img)){
                $first_img = "/wp-content/default.png";
            }
            return $first_img;
    }
    

    if you insert this function to your functions.php of your theme you can insert

    <img src="<?php echo catch_that_image(); >" width="50" height="50" alt="<?php the_title(); ?>" />
    

    in your single.php and index.php

    This function will catch the first image in ever post and will display it, if no one is available - it will use one Default image which you can change...

    Or another way:

    <?php $image = get_post_meta($post->ID, 'postimage', true); ?>
    
    <img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" />
    

    If you put this in your index.php or single.php it will use the image given in field "postimage" (customfield in posts/pages).