0

I'de like to have a mysql query on a wordpress database that recover the title and the first image link of the last 6 posts.

Wordpress core functions are not permitted because I'd like to show them on an external site. In other words I need the pure mysql query.

I'm able to show the titles in this way:

$result = mysql_query("select * FROM wp_posts WHERE post_status='publish' AND post_type='ad_listing' ORDER BY id desc limit 6" ,$db);
while ($records = mysql_fetch_assoc($result)) {
  echo '<li>'.$records['post_title'] ."</li>";
}

But how to recover the first image (if exists) attached to these posts?

2
  • Where are the images? Commented Mar 20, 2013 at 21:16
  • the images links are in the wordpress database (post_type=attachement, guid=url_to_the_image), the files are located in the upload folder of the wordpress site Commented Mar 20, 2013 at 21:19

1 Answer 1

1

For your image records in the wp_posts table, does the post_parent point back at the published page? Mine does not, and if yours doesn't either, then you need to search through the post_content field for each published page, looking for img tags (or whatever tag you use for your images).

From other articles I've read, it appears that sometimes post_parent for an image points back at the parent page. If this is true for your database, then you should be able to do something like this:

SELECT 
    post.id AS post_id, 
    post.post_title, 
    post.guid AS post_url, 
    image_detail.id AS image_id, 
    image_detail.post_title AS image_title, 
    image_detail.guid AS image_url
FROM wp_posts AS post
LEFT JOIN (
    SELECT post_parent, MIN( id ) AS first_image_id
    FROM wp_posts
    WHERE post_type = 'attachment'
        AND post_mime_type LIKE 'image/%'
    GROUP BY post_parent
    ) AS image_latest 
    ON post.id = image_latest.post_parent
LEFT JOIN wp_posts AS image_detail 
    ON image_detail.id = image_latest.first_image_id
WHERE post.post_status = 'publish';
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer but it don't work for me. I confirm that in my wordpress db post_parent point back at the published page
After some adaptations to my case, it now works. Thank you very much.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.