WordPress.org

Ready to get started?Download WordPress

Forums

Display only the last post with image attached to it (2 posts)

  1. rionbr
    Member
    Posted 5 years ago #

    Hi there,

    I´m fairly new to WP and I came up with a problem I couln´t find a exactly solution for.

    I have a website with a WP blog running on it. I need that on index page the WP loop displays only the latest post with a thumb/image attached to it.

    Why? Because if it shows a post without the thumb my layout gets broken.

    I´m using "$posts = get_posts('numberposts=1');" but it displays all the posts with or without child.

  2. rionbr
    Member
    Posted 5 years ago #

    So, I´ve came up with the following solution, please, if anyone has a better one, post it here.

    $posts = get_posts('');
    foreach($posts as $post) :
        setup_postdata($post);
        //Attachements
        $files = get_children("post_parent=".$post->ID."&post_type=attachment&post_mimi_type=image");
        if($files) {
            $keys = array_keys($files);
            $num = $keys[0];
            $thumb = wp_get_attachment_thumb_url($num);
            break 1;
        }
    endforeach;

    It simply breaks the foreach when it founds a child inside a post

Topic Closed

This topic has been closed to new replies.

About this Topic