获取特定帖子类型的所有帖子的附件

时间:2012-05-16 作者:dnagirl

我正在制作一个小部件,显示最近自定义帖子中的一组图像。我要运行以下查询:

SELECT p.* 
FROM wp_posts p
WHERE post_type=\'attachment\'
AND post_mime_type LIKE \'image%\'
AND post_parent IN (
  SELECT ID
  FROM wp_posts
  WHERE post_type =\'my_custom_post_type\'
)
ORDER BY post_date DESC
LIMIT 10;
并接收附件对象数组。我不清楚这样做的规范WordPress方法。我应该从哪里开始?

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

仅仅为了使用一些不是为这样的用例设计的内置API函数而运行两个循环似乎有点浪费。

我认为您最好将SQL与wpdb 类--更快、更干净。

示例(使用修改后的SQL):

<?php
function wpse52315_get_attach()
{
    global $wpdb;
    $res = $wpdb->get_results("select p1.*
        FROM {$wpdb->posts} p1, {$wpdb->posts} p2
        WHERE p1.post_parent = p2.ID 
           AND p1.post_mime_type LIKE \'image%\'
           AND p2.post_type = \'your_cpt\'
        ORDER BY p2.post_date
        LIMIT 10;"
    );
    return $res;
}

SO网友:mrwweb

我推荐的是WP_Query 用于循环遍历所有自定义post类型post,然后get_posts() 检索每篇文章的附件。下面是一个未经测试的代码段,它可以完成您想要的功能:

// Setup array for storing objects
$my_attachment_objects = array();

// Arguments for custom WP_Query loop
$my_cpts_args = array(
    \'post_type\' => \'my_custom_post_type\',
    \'posts_per_page\' => 10
);

// Make the new instance of the WP_Query class
$my_cpts = new WP_Query( $my_cpts_args );

// And Loop!
if( $my_cpts->have_posts() ) : while( $my_cpts->have_posts() ) : $my_cpts->the_post();

    // arguments for get_posts
    $attachment_args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' => \'image\',
        \'post_status\' => null, // attachments don\'t have statuses
        \'post_parent\' => $post->ID
    );
    // get the posts
    $this_posts_attachments = get_posts( $attachment_args );
    // append those posts onto the array
    $my_attachment_objects[$post->ID] = $this_posts_attachments; // make an array with the post_id as the key, just in case that\'s useful

endwhile; endif; wp_reset_postdata();
希望这有帮助。

SO网友:Jeremy Jared

可能是这样的:

<?php
  $args = array( \'post_type\' => \'portfolio\', \'posts_per_page\' => 10 );
  $loop = new WP_Query( array ( \'orderby\' => \'title\', \'order\' => \'DESC\' ) );  
  while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo \'<div class="entry-content">\'; the_content();
    echo \'</div>\';
  endwhile;
  ?>

SO网友:Philip Downer

如果您只对特定帖子类型的附件数量感兴趣,则可以将Chris的功能稍微修改为以下内容:

<?php
function myprefix_image_count() {
    global $wpdb;
    $res = $wpdb->get_var("select COUNT(*)
        FROM {$wpdb->posts} p1, {$wpdb->posts} p2
        WHERE p1.post_parent = p2.ID
           AND p1.post_mime_type LIKE \'image%\'
           AND p2.post_type = \'your_cpt_name\'
        ORDER BY p2.post_date;"
    );
    $imageCount = (int)$res;
    return $imageCount;
}
?>

结束

相关推荐

Query not sorting DESC

我正在使用以下查询:<?php $postslist = new WP_Query(\'meta_key=Ordermetakey&orderby=meta_value_num&order=ASC&posts_per_page=5\'); 对frontpage上的小帖子列表进行排序,以显示最新的帖子。它需要通过一个元键对它们进行排序并进行描述。奇怪的是,它显示了帖子的ASC,尽管我已经将ASC放在了这个查询中。元键的值是日期-时间戳:例如:120403=03-04-