Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading