Question

I get the first image from post whith this code:

function 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)){
$images = array(
     'white5px.jpg',
 );
$image  = $images[array_rand($images)];
$first_img = "/wp-content/themes/tabs/images/" . $image . "";
}
return $first_img;}
?>

<img src="<?php echo first_image() ?>"title="<?php the_title(); ?>" alt="<?php the_title(); ?>"/>

Everything works fine except when I use the galery - the image not displayed. Live example:http://beardhouse.com.ua/?cat=2 Why it doesn't work and how I can solve this problem?

No correct solution

OTHER TIPS

Everything works fine except when I use the galery - the image not displayed.

Galleries are not stored in the post body as full img tags, which is what your regex looks for. A gallery is saved to the post body as a shortcode which is processed on display and transformed into the gallery you see.

That is, if you echo $post->post_content what you will see is something like this:

[gallery ids="729,732,731,720"]

The quick and dirty solution would be to process that shortcode before your regex gets involved.

$content = do_shortcodes($post->post_content);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
$first_img = $matches [1] [0];

I can't help but think that that is a somewhat clumsy and inefficient solution. Most images in WordPress are "attachments" to the post, so you might be better off querying for attachments directly, as per this example from the Codex:

function echo_first_image( $postID ) {
    $args = array(
        'numberposts' => 1,
        'order' => 'ASC',
        'post_mime_type' => 'image',
        'post_parent' => $postID,
        'post_status' => null,
        'post_type' => 'attachment',
    );

    $attachments = get_children( $args );

    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )  ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );

            echo '<img src="' . wp_get_attachment_thumb_url( $attachment->ID ) . '" class="current">';
        }
    }
}

To get First Image of Post Enter this code in Function.php file

 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 = $matches [1] [0];if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";}return $first_img;}

}

add this code in post loop

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top