如何运行WP_QUERY以仅从特定类别检索帖子的附件?

时间:2012-06-26 作者:aalaap

我有一个WP博客,有几个页面、帖子和几个类别。我想写一个循环来检索附在帖子(而不是页面)上的图像,只检索特定类别及其子级的图像。类别id为60。

这是WP\\U查询调用:

$my_query = new WP_Query( array(
  \'post_type\' => \'attachment\',
  \'cat\' => \'60\',
  \'post_mime_type\' =>\'image\',
  \'posts_per_page\' => $batch_size,
  \'nopaging\' => false,
  \'post_status\' => \'all\',
  \'post_parent\' => null,
  \'meta_key\' => \'my_hash\',
  \'orderby\' => \'meta_value\'
) );
但我什么也得不到!

我做错了什么?

3 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

您需要首先抓取帖子,然后抓取作为所述帖子子级的附件。

$my_query = new WP_Query( array(
    \'meta_key\' => \'my_hash\',
    \'nopaging\' => true,
    \'orderby\' => \'meta_value\',
    \'fields\' => \'ids\',
    \'cat\' => \'60\',
));

if ( $post_ids = $my_query->get_posts() ) {
    $post_ids = implode( \',\', $post_ids );
    $atts_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_parent IN($post_ids) AND post_type = \'attachment\'" );   

    $my_query->query( array(
        \'posts_per_page\' => $batch_size,
        \'post_mime_type\' =>\'image\',
        \'post_status\' => \'all\',
        \'post_type\' => \'attachment\',
        \'post__in\' => $atts_ids,
    ));
}

SO网友:Tom J Nowell

附件帖子没有类别,他们父母的帖子有类别,所以你有两个步骤的问题。

查找类别(60?)中post类型的post的IDpost_parent 这是我们在第一次查询中找到的列表

SO网友:Alexei Isaenko

如果要获取类别和子类别的图像链接,应使用以下选项:

    global $wpdb;
$id = 60; // your cat id
$myrows = $wpdb->get_results( "SELECT p2.ID, p2.guid ".
    "FROM $wpdb->posts as p1, $wpdb->posts as p2, $wpdb->term_relationships as tr, $wpdb->term_taxonomy as tt  ".
    "WHERE ".
    "((tr.term_taxonomy_id = $id AND ".
    "p1.ID = tr.object_id) OR ".
    "(tt.parent = $id AND ".
    "tr.term_taxonomy_id = tt.term_taxonomy_id AND ".
    "p1.ID = tr.object_id)) AND ".
    "p1.post_status = \'publish\' AND ".
    "p2.post_parent = p1.ID AND ".
    "p2.post_mime_type LIKE \'image%\'".
    "GROUP BY p2.ID".
    "<= 5". // you able to limit the db answer
    "", ARRAY_A );
print_r( $myrows );

结束