1

how can i set my thumbnail to use the first image on my post? most time i use bbcode( [img] ) to place images on my post, i want them to be use as well,

have tried so many suggestion, but none meet my needs,

below are some of the codes that have tried.

<?php if ( has_post_thumbnail() ) {
  the_post_thumbnail();
} else { ?>
  <img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>

i try adding this on my function.php

//function to call first uploaded image in functions file
function main_image() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment
&post_mime_type=image&order=desc');
if($files) :
  $keys = array_reverse(array_keys($files));
  $j=0;
  $num = $keys[$j];
  $image=wp_get_attachment_image($num, 'large', true);
  $imagepieces = explode('"', $image);
  $imagepath = $imagepieces[1];
  $main=wp_get_attachment_url($num);
    $template=get_template_directory();
    $the_title=get_the_title();
    print "<img src='$main' alt='$the_title' class='frame' />";
  endif;
}
1
  • Fix your code please if you want help here. Aug 1, 2015 at 17:22

1 Answer 1

1

You can try this function, in your functions.php file.

// automatically retrieve the first image from posts
function get_first_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all( '/<img .+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
    $first_img = $matches[1][0];
    if ( empty( $first_img ) ) {
        // defines a fallback imaage
        $first_img = get_template_directory_uri() . "/images/default.jpg";
    }
    $first_img = '<img src="' . $first_img . '" alt="Post Image" />';
    return $first_img;
}

This function search for first image tag in content and returns it. Then in your theme you can call image like this.

<?php
    if ( get_the_post_thumbnail( $post_id ) != '' ) {
        the_post_thumbnail();
    } else {
        echo get_first_image();
    }
?>
1
  • thanks @robert , d code work well, but it did nt use image posted with bbcode(img) as thumbnail, pls i need the one dat can use image from external link as thumbnail, tanks
    – Solo Solo
    Aug 1, 2015 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.