2

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

我设法获得了标题、内容、图像 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"...

我可以看到我得到了图像 id,c.id它所需要的只是另一个JOINwp_postmetawhere 字段中获取数据meta_key="_wp_attachment_metadata" and post_id=c.id

谁能帮我完成查询?谢谢!

4

3 回答 3

0

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

  • 做一个插件
  • 或在您的脚本中包含 wp-load.php

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

于 2012-04-18T07:51:51.730 回答
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';
于 2019-05-29T04:51:36.973 回答
-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;?>
于 2012-04-19T15:02:26.487 回答