2013-03-20 135 views
0

我想在wordpress數據庫上有一個mysql查詢,用於恢復標題和最近6篇文章的第一個圖像鏈接。關於Wordpress數據庫的MySQL查詢

WordPress的核心功能是不允許的,因爲我想在外部網站上顯示它們。換句話說,我需要純粹的mysql查詢。

我能夠表現出這樣的標題:

$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>"; 
} 

但如何恢復第一個圖像(如果存在)連接到這些帖子?

+0

圖像在哪裏? – Kermit 2013-03-20 21:16:25

+0

圖片鏈接在wordpress數據庫中(post_type = attachement,guid = url_to_the_image),這些文件位於wordpress站點的上傳文件夾中 – Avionicom 2013-03-20 21:19:39

回答

1

對於wp_posts表中的圖像記錄,是否將post_parent點返回到已發佈頁面?我的沒有,如果你的也沒有,那麼你需要搜索每個發佈頁面的post_content字段,尋找img標籤(或者你用於圖片的任何標籤)。

從我讀過的其他文章看來,有時圖像的post_parent指向父頁面。如果您的數據庫的確如此,那麼您應該可以這樣做:

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'; 
+0

謝謝你的回答,但它對我不起作用。我確認在我的wordpress db post_parent指向已發佈頁面 – Avionicom 2013-03-21 20:47:36

+0

經過對我的案例的一些改編後,它現在可以工作。非常感謝你。 – Avionicom 2013-03-22 16:16:07