Wordpress not returning all posts

While building cli app for wordpress to delete all posts i run into a problem: get_posts is not returning all posts.

I tried get_posts with all possible arguments while taking care of not forgeting to override some default settings, for example, post_type or post_status, but changing these didn't help.

Funny thing is wordpress is showing posts on my home page and in categories but not listing them trough get_posts.

After tracing what happens after calling get_posts, which is using WP_Query and then passing through huge procedure of building query. After getting to the final SQL query result and putting dump under that line:

$this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";

print_r($this->request);die();

I got this:

SELECT   wp_posts.* FROM wp_posts  WHERE 1=1  AND ( 
  wp_posts.ID NOT IN (
                SELECT object_id
                FROM wp_term_relationships
                WHERE term_taxonomy_id IN (167,174,175,177,184,185,186,190,191,196,205,209,211,219,224,229,233,239,247,251,252,254,268,272,313,317,324,342,344,346,355,358,365,367,373,378,419,434,435,477,505,517,527,528,530,531,532,534,536,537,538,540,547,548,553,554,558,562,564,565,566,572,573,580,587,588,589,596,599,602,657,723,772,920,954,1149,1383,1393,1435,1436,1438,1446,1450,1484,1487,1544,1546,1602,1637,1638,1648,1747,1750,1861,1882)
            )
) AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish' OR wp_posts.post_status = 'trash')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 100

The point is, every plugin can modify query, so it is hard to trace it.

Lets try disabling plugins with changing plugin dir (put anything there)

define( 'WP_PLUGIN_DIR', '/wp-content/plugins.off' );

After that output SQL looked like:

SELECT   wp_posts.* FROM wp_posts  WHERE 1=1  AND wp_posts.post_type = 'post' AND ((wp_posts.post_status = 'publish' OR wp_posts.post_status = 'trash'))  ORDER BY wp_posts.post_date DESC LIMIT 0, 100

Now all posts will be listed.

Possible problems can be if you need this functionality when it is too late to define WP_PLUGIN_DIR. Solution is to make custom SQL query and get ids.

Author

I plan to write more articles about common laravel components. If you are interested let’s stay in touch.
comments powered by Disqus