douzhi1879 2016-02-21 07:12
浏览 5
已采纳

列出特定类别的所有附件

I want to use this script to list all the attachments paths for posts of a particular category:

<?php
    $args = array( 
        'post_type'     => 'attachment', 
        'numberposts'   => -1,
        'category'      => 61
    ); 
    $the_attachments = get_posts( $args );
    if ($the_attachments) {
        foreach ( $the_attachments as $post ) {
            setup_postdata($post);
            echo get_attached_file( $post->ID ) . "<br />";
        }
    } wp_reset_query();
    ?>

But the problem is it doesn't do anything unless I remove the 'category' arg, in which case it shows ALL attachment paths regardless. But I only want it for category 61.

I've triple checked and there are indeed posts that contain attachments in category 61.

What am I doing wrong?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanpai6581 2016-02-21 07:52
    关注

    Category is not taxonomy for attachment post type. post and attachment are two different post types and category is attached to post and attachments are children of post.

    So first get the all post in that category

    $cat_posts = get_posts(array(
        'category' => 61,
        'numberposts' => -1
    ));
    

    Create the post IDs array so we can use in WP_Query

    $parent_ids = array_map('get_post_ids', $cat_posts);
    
    function get_post_ids($post_obj) {
        return isset($post_obj->ID) ? $post_obj->ID : false;
    }
    

    Now get all the children of all parent IDs

    $the_attachments = get_posts(array(
        'post_parent__in' => $parent_ids,
        'numberposts' => -1,
        'post_type' => 'attachment'
    ));
    

    Display the attachments

    if ($the_attachments) {
        foreach ( $the_attachments as $my_attachment ) {
            echo wp_get_attachment_image($my_attachment->ID);
        }
    }
    

    Note: post_parent__in is only available from version 3.6

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比