Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress get_posts() not returning all posts with post_type=attachment

Tags:

php

wordpress

I am trying to get a list of all videos from Wordpress' media library. I do it from outside the regular WP loop, hence including wp-load.php. However, I get returned 0 posts with this code (though there are actually 4 videos):

include('../../../wp-load.php');

$args = array( 
  'post_type' => 'attachment', 
  'post_mime_type' => 'video', 
  'numberposts' => -1, 
  'posts_per_page'=>-1, 
  'suppress_filters' => true, 
  'post_status' => 'any', 
  'post_parent' => null
); 
$attachments = get_posts( $args );
echo(count($attachments));
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        echo('<br />');
        echo wp_get_attachment_url( $post->ID, false );
        echo('<br /><br />');
    }
    wp_reset_postdata();
}

However, the issue does not seem to be related to the videos directly (or only): If I remove the 'post_mime_type' => 'video' argument from the query, I get returned only 16 instead of 121 total attachments (images, sounds, videos) in my media library. I am really starting to lose my mind on this issue...

like image 826
Florian Ubr Avatar asked Dec 20 '25 19:12

Florian Ubr


1 Answers

Heureka! After hours of trying out nearly everything I found the cause of this issue: the plugin Polylang.

Long story short, if Polylang is installed in your Wordpress installation, one seems to have to provide another argument for the get_posts() function: it's called lang!

It can be an empty string to list simply all assets, or one of the specific language tags used by Polylang in the specific Wordpress installation. So the finally working code must look like this:

include('../../../wp-load.php');

$args = array('lang' => '', 'post_type' => 'attachment', 'post_mime_type' => 'video', 'numberposts' => -1, 'posts_per_page'=>-1, 'suppress_filters' => true, 'post_status' => 'any', 'post_parent' => null); 
$attachments = get_posts( $args );
echo(count($attachments));
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        echo('<br />');
        echo wp_get_attachment_url( $post->ID, false );
        echo('<br />');echo('<br />');
    }
    wp_reset_postdata();
}

I really hope this can help somebody else save some valuable time!

This link helped in finding my solution: http://polylang.wordpress.com/documentation/documentation-for-developers/general/

like image 99
Florian Ubr Avatar answered Dec 22 '25 12:12

Florian Ubr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!