我使用以下内容将类别分配给我的WordPress媒体库(在functions.php):
function wptp_add_categories_to_attachments() {
    register_taxonomy_for_object_type( \'category\', \'attachment\' );
}
add_action( \'init\' , \'wptp_add_categories_to_attachments\' );
 每个媒体库项目都分配了特定的类别。。。我有一些从媒体库返回最新5幅图像的代码,如下所示(在
footer.php):
<?php
    $args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' => \'image\',
        \'orderby\' => \'post_date\',
        \'order\' => \'desc\',
        \'posts_per_page\' => \'5\',
        \'post_status\' => \'inherit\'
    );
    query_posts($args);
?>
    <?php if ( have_posts() ) : ?>
        <div class="wrap">
            <h5><span>Recently</span> Added</h5>
            <ul>
                <?php
                    while ( have_posts() ) : the_post();
                    $url = get_attachment_link(get_post_thumbnail_id());
                    $image = wp_get_attachment_image_src(get_the_ID(), "thumbnail");
                ?>
                    <li><a href="<?php echo $url; ?>"><img src="<?php echo $image[0]; ?>"></a></li>
                <?php endwhile; ?>
            </ul>
        </div>
    <?php else : ?>
        <div class="wrap">
            <h5>Oops...</h5>
            <p><?php _e( \'Sorry, no posts matched your criteria.\' ); ?></p>
        </div>
    <?php endif; ?>
<?php wp_reset_query(); ?>
 我想做的是,如果图像具有指定的类别,则只返回这些图像。
非常感谢您的帮助。
谢谢,乔希
 
                    最合适的回答,由SO网友:Josh Rodgers 整理而成
                    我找到了解决办法!
我的代码更改了很多。。。
下面是functions.php 文件如下(未更改):
function wptp_add_categories_to_attachments() {
    register_taxonomy_for_object_type( \'category\', \'attachment\' );
}
add_action( \'init\' , \'wptp_add_categories_to_attachments\' );
 但这里是
footer.php, 它从媒体库返回图像,但仅从指定的类别返回:
<?php
    $args = array(
        \'post_type\' => \'attachment\',
        \'numberposts\' => \'5\',
        \'category_name\' => \'your-category-name\'
    );
    $images = get_posts($args);
    if (!empty($images)) {
?>
    <div class="wrap">
        <h5><span>Recently</span> Added</h5>
        <ul>
            <?php
                foreach ($images as $image) {
                    $attachment_link = get_attachment_link( $image->ID );
                    echo "<li><a href=\'".$attachment_link."\'>".wp_get_attachment_image($image->ID)."</a></li>";
                }
            ?>
        </ul>
    </div>
<?php } else { ?>
    <div class="wrap">
        <h5>Oops...</h5>
        <p><?php _e( \'Sorry, no posts matched your criteria.\' ); ?></p>
    </div>
<?php } ?>
 我本可以在添加时调整现有代码
category_name => \'your-category-name\' 给我的
$args, 但这是一种更简单的方法,并且做了完全相同的事情。。。它只是使用
get_posts 而不是
query_posts.