Home > Mobile >  Using get_posts() to return media files of a specific category only returns some of the posts
Using get_posts() to return media files of a specific category only returns some of the posts

Time:06-25

I have uploaded 11 jpg files to the media library using the normal admin dashboard media library tools. These will be used for background images. In the media file editor I applied a new category called "pw-background". So now, 11 media files have pw-background as their category. In the function.php of my child theme, I added the following code to return all posts with the new category. Here is the code:

function adjust_background_image(){
        $args = array(
                        'category_name' => 'pw-background',
                        'post_type' => 'attachment'
                    );
        $attachments = get_posts($args);
        echo "<pre>";
        print_r($attachments); // An array with only 5 elements is returned. 
        echo "</pre>";
}
add_action('wp_head', 'adjust_background_image');

When I run the page, what happens is that only the last five media files I uploaded and tagged with the pw-background are returned. So, count($attachments) = 5 when it should equal 11. The code returns media files with the correct category, but only the last five out of a total of 11 images with the same category.

Why is the function returning only some of the posts, and how do I get all of the posts of a given category?

CodePudding user response:

@TARKUS you should add 'numberposts' parameter to the $args array to control the number of posts retrieved from get_posts() wordpress function, as specified in the codex:

https://developer.wordpress.org/reference/functions/get_posts/

Hope this helps

  • Related