如何手动查询帖子标题,内容和图片附件缩略图?

时间:2012-04-18 04:11:15

标签: mysql wordpress

我正在尝试从外部php文件手动查询wordpress数据库,我想提取最后3个帖子:标题,内容,最后(或第一)图像,对于该图像,从wp_postmeta我想得到缩略图网址。

我设法得到标题,内容,图片ID,但我无法弄清楚如何添加另一个连接来获取图片缩略图。这就是我所拥有的:

SELECT a.post_title title, max(c.guid) img_url, a.ID id
FROM wp_posts a

LEFT JOIN
(select post_parent, max(post_date_gmt) as latest_image_date from wp_posts
where post_type='attachment' GROUP BY post_parent) b 
on a.id=b.post_parent

LEFT JOIN wp_posts c
on c.post_parent=a.id 
and c.post_type='attachment' 
and b.latest_image_date = c.post_date_gmt where c.guid IS NOT NULL

GROUP BY a.post_title ORDER BY a.ID

图片缩略图位于wp_postmeta (meta_id, post_id, meta_key, meta_value)表格中,如下所示:58435, 6711, _wp_attachment_metadata, a:6:{s:5:"width";s:4:"1024";s:6:"height";s:3:"683"...

我可以看到我在c.id中获取了图片ID,而其所需的只是另一个JOIN,也可以从wp_postmeta获取meta_key="_wp_attachment_metadata" and post_id=c.id字段的数据。

任何人都可以帮我完成查询吗?谢谢!

3 个答案:

答案 0 :(得分:0)

您应该节省时间并使用wordpress功能:

  • 制作插件
  • 或在脚本中包含wp-load.php

https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files

答案 1 :(得分:0)

我知道这是一篇旧文章,但是在这里可以帮助将来的求职者

根据需要更新查询。当前查询将选择带有附件的帖子。它返回附件ID和guid,帖子ID和标题以及类别名称和term_id。

SELECT DISTINCT p.ID,p.post_title, a.ID as attach_id, a.guid, t.name, t.term_id FROM $wpdb->posts as a
LEFT JOIN $wpdb->posts as p on p.ID = a.post_parent
AND a.post_type = 'attachment' AND a.post_mime_type = 'image/png'

JOIN $wpdb->term_relationships as tr on tr.object_id = p.ID
JOIN $wpdb->terms as t on t.term_id = tr.term_taxonomy_id
JOIN $wpdb->term_taxonomy as tt on tt.term_id = t.term_id
AND tt.taxonomy = 'category'

AND p.post_type = 'post'
AND p.post_status = 'publish';

答案 2 :(得分:-1)

最后我选择了另一个解决方案(至少是临时的),因为它增加了横向功能:我创建了一个完全空的自定义页面(我不得不手动删除一些操作/过滤器以使其为空)在另一个站点(一个包括)以json格式导出数据。我获取该数据并在当前站点中根据需要进行打印。

<?php
$args= array(
    'posts_per_page' => 6
    //if there are sticked posts they will also appear beside the 2 if we run this in a separate php file, not included in theme
);
$ii = 0;
query_posts($args);
if( have_posts() ) :


  while ( have_posts() ) : the_post();

    $permalink = get_permalink();
    $titlu = get_the_title();
    $excerpt = get_the_excerpt();

    $args = array(
        'post_type'      => 'attachment',
        'post_parent'    => $post->ID,
        'post_status'    => 'inherit',
        'numberposts'    => 1
    );
    $images = get_posts($args);
    $j = 1;
        foreach ($images as $i) :

        $ii++;//am preluat doar o poza, e ok numaratoarea
        $j++;
        $poza_thumb = wp_get_attachment_image_src($i->ID, 'thumbnail');
        $arr[$ii] = array('titlu' => $titlu, 'url' => $permalink, 'poza_thumb' => "".$poza_thumb[0], 'poza_width' => "".$poza_thumb[1], 'poza_height' => "". $poza_thumb[2], 'articol' => $excerpt);

        endforeach;

    endwhile;

    echo json_encode($arr);//we send json as array
else :

endif;?>