How pre_get_posts filter by roles in WP Admin

I’d make 2 queries. This would look something like this : function add_role_filter_to_posts_administration(){ //execute only on the ‘post’ content type global $post_type; if($post_type == ‘post’){ $user_role=””; // Get all user roles $user_roles = array(); foreach ( get_editable_roles() as $key => $values ) : $user_roles[ $key ] = $values[‘name’]; endforeach; // Set a selected user role … Read more

pre_get_posts on a page

Explaining the object. You don’t have to manually force data into those class properties. The whole $wp_query object has a bunch of internal methods that you should use to set values. Here’s an example: public function query( $query ) { if ( ‘SOME_POST_TYPE’ !== $query->get( ‘post_type’ ) OR ! $query->is_main_query() OR ! $query->is_archive() OR ! … Read more

Obliterate the main query and replace it

When ‘pre_get_posts’ is fired, there are a lot of things that WordPress has already done like setup all the query variables (also the query you don’t send) and setup all the conditional properties (all the is_* properties). So, if you want completely replace the query you should reset all that things and set your own. … Read more

Sticky Posts exceed posts per page limit

Here is an approach to account for sticky posts by getting the number of sticky posts (if any) and include that in the calculation posts_per_page parameter: add_action(‘pre_get_posts’, ‘ad_custom_query’); function ad_custom_query($query) { if ($query->is_main_query() && is_home()) { // set the number of posts per page $posts_per_page = 12; // get sticky posts array $sticky_posts = get_option( … Read more