在附件查询帖子中添加类别名称


Add category name in attachment query posts

如何显示特定类别的附件?

我试着添加

'category_name' => 'my-category-slug'

但它不起作用

 <?php $attachments = get_children(array(
     'post_parent' => null,
     'post_type' => 'attachment',
     'post_mime_type' => 'image',
     'posts_per_page' => 35,
     'post_status' => 'any',
     'exclude'  => get_post_thumbnail_id(),
     'orderby' => 'rand')); 
     foreach($attachments as $att_id => $attachment) {
         $full_img_url = wp_get_attachment_url($attachment->ID);
         echo '<li>';
         echo '<a href="' . wp_get_attachment_url($attachment->ID) . '"data-lightbox="galerija-front">';
         echo wp_get_attachment_image($attachment->ID, 'galerija-front', false, $attr);
         echo '</a>';
         echo '</li>'; 
     }
?>

您可以使用get_posts而不是get_children。此外,您是否尝试过使用tax_query并指定类别的分类法和术语?

示例:

$attachments = get_posts(array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'posts_per_page' => 35,
    'post_status' => 'any',
    'post__not_in'  => array(get_post_thumbnail_id()),
    'orderby' => 'rand',
    'tax_query' => array(
        array(
            'taxonomy' => 'category_name',
            'field' => 'slug',
            'terms' => 'my-category-slug'
        )
    )
));

其中"category_name"answers"my category-slug"分别是分类法和slug。