Catch main image from last post in WordPress

0

I need to display the last post posted WordPress blog in a CakePHP application and I'm doing it as follows:

$post = $this->Post->query(
    "SELECT
        posts.id,
        posts.post_title AS title,
        posts.post_date,
        posts.guid,
        files.meta_value AS filepath
    FROM
        wp_posts posts
    INNER JOIN wp_posts attachments ON posts.ID = attachments.post_parent
    INNER JOIN wp_postmeta files ON attachments.ID = files.post_id
    WHERE files.meta_key = '_wp_attached_file' ORDER BY posts.post_date DESC LIMIT 1"
);

So, I'm getting the last post, but the image is not the one that is registered to be featured on the blog, what would be a way to search only the main photo of that post?

    
asked by anonymous 20.08.2014 / 01:59

1 answer

1

I was able to do the following, but it was a bit strange:

    $post = $this->Post->query(
        "SELECT
            posts.id,
            posts.post_title AS title,
            posts.post_date,
            posts.guid
        FROM
            wp_posts posts
        INNER JOIN wp_posts attachments ON posts.ID = attachments.post_parent
        INNER JOIN wp_postmeta files ON attachments.ID = files.post_id
        ORDER BY posts.post_date DESC LIMIT 1"
    );

    $picture = $this->Post->query(
        "SELECT picture.guid FROM wp_postmeta
        INNER JOIN wp_posts picture ON wp_postmeta.post_id=picture.ID
        WHERE post_parent = {$post[0]['posts']['id']} AND meta_key = '_wp_attached_file'
        ORDER BY post_date DESC LIMIT 1"
    );

    $post[0]['posts']['picture'] = $picture[0]['picture']['guid'];

    $this->set('post', $post);
    
20.08.2014 / 02:47