Using WordPress ‘posts_pre_query’ PHP filter

The posts_pre_query WordPress PHP filter allows you to modify the posts array before the actual query takes place. By returning a non-null value, you can bypass the default WordPress post queries.

Usage

add_filter('posts_pre_query', 'your_function_name', 10, 2);

function your_function_name($posts, $query) {
    // your custom code here
    return $posts;
}

Parameters

  • $posts (WP_Post[]|int[]|null) – Return an array of post data to short-circuit WP’s query, or null to allow WP to run its normal queries.
  • $query (WP_Query) – The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: posts_pre_query

Examples

Display only sticky posts

Display only sticky posts on the homepage by modifying the posts array.

add_filter('posts_pre_query', 'display_only_sticky_posts', 10, 2);

function display_only_sticky_posts($posts, $query) {
    if (is_home() && $query->is_main_query()) {
        $sticky_posts = get_option('sticky_posts');
        return get_posts(array('post__in' => $sticky_posts));
    }
    return $posts;
}

Exclude a category

Exclude posts from a specific category by modifying the posts array.

add_filter('posts_pre_query', 'exclude_specific_category', 10, 2);

function exclude_specific_category($posts, $query) {
    if (!is_admin() && $query->is_main_query()) {
        $excluded_category = get_cat_ID('Category Name');
        $query->set('category__not_in', array($excluded_category));
    }
    return $posts;
}

Custom post type archive

Display a custom post type archive by modifying the posts array.

add_filter('posts_pre_query', 'custom_post_type_archive', 10, 2);

function custom_post_type_archive($posts, $query) {
    if (is_post_type_archive('your_custom_post_type')) {
        $args = array(
            'post_type' => 'your_custom_post_type',
            'posts_per_page' => 10
        );
        return get_posts($args);
    }
    return $posts;
}

Custom search results

Display custom search results based on post title only.

add_filter('posts_pre_query', 'custom_search_results', 10, 2);

function custom_search_results($posts, $query) {
    if (is_search() && $query->is_main_query()) {
        $search_term = get_search_query();
        $args = array(
            'post_type' => 'post',
            'title_like' => $search_term
        );
        return get_posts($args);
    }
    return $posts;
}

Display posts from a specific author

Display posts from a specific author by modifying the posts array.

add_filter('posts_pre_query', 'display_posts_from_author', 10, 2);
function display_posts_from_author($posts, $query) {
if (!is_admin() && $query->is_main_query()) {
$author_id = 1; // Replace with the desired author ID
$query->set('author', $author_id);
}
return $posts;
}