简体   繁体   中英

Wordpress loop media by “uploaded By”

I have a webpage that I want to display images that are uploaded by a certain author.

In the backend if I look at media, each image has an 'Uploaded By' attribute, and then it says the authors name.

example http://www.discoveryourwonder.com/wp-content/uploads/2015/05/sg.png

I've tried using this loop:

<?php
// The Query
$args = array(
   'author'      => $author_name_variable, // Replace with author id
   'post_status' => 'any',
   'post_type'   => 'attachment'
);
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . the_content() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>

It is very buggy. Some authors it will show every media file, others none; the rest are just inaccurate. It's a real blind shot :/

The goal is to loop through all the media files, and then post the_content() of all files with the corresponding Uploaded By name.

I would be grateful if someone could comment as to why an ID is more reliable than a slug in the 'author' argument.

I figured out a solution. Apparently the 'author' argument does not like usernames, so I converted it to ID and it works now. I used get_user_by( 'slug', $username ); to get all the information of the particular username, and then assigned that array to a variable. I then filtered the variable to only use the ID and passed that through the arguments.

Here's the working loop:

<?php
// The Query
$profileid = get_user_by( 'slug', $username );
$args = array(
   'author'      => $profileid->id, // Replace with author id
   'post_status' => 'inheret',
   'post_type'   => 'attachment'
);
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . the_content() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM