Using WordPress ‘posts_distinct_request’ PHP filter

posts_distinct_request is a WordPress PHP filter that allows you to modify the DISTINCT clause of a query.

This is especially useful for caching plugins.

Usage

add_filter('posts_distinct_request', 'your_custom_function', 10, 2);

function your_custom_function($distinct, $query) {
    // your custom code here
    return $distinct;
}

Parameters

  • $distinct (string): The DISTINCT clause of the query.
  • $query (WP_Query): The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: posts_distinct_request

Examples

Remove DISTINCT Clause

Remove the DISTINCT clause from the query to retrieve all rows.

function remove_distinct_clause($distinct, $query) {
    $distinct = '';
    return $distinct;
}
add_filter('posts_distinct_request', 'remove_distinct_clause', 10, 2);

Add Custom DISTINCT Clause

Add a custom DISTINCT clause to the query.

function custom_distinct_clause($distinct, $query) {
    $distinct = 'DISTINCT custom_column';
    return $distinct;
}
add_filter('posts_distinct_request', 'custom_distinct_clause', 10, 2);

Modify DISTINCT Clause Based on Custom Post Type

Modify the DISTINCT clause only for a specific custom post type.

function modify_distinct_for_custom_post_type($distinct, $query) {
    if ('custom_post_type' === $query->get('post_type')) {
        $distinct = 'DISTINCT custom_column';
    }
    return $distinct;
}
add_filter('posts_distinct_request', 'modify_distinct_for_custom_post_type', 10, 2);

Modify DISTINCT Clause Based on Category

Modify the DISTINCT clause only for posts in a specific category.

function modify_distinct_for_category($distinct, $query) {
    if ($query->is_category('your-category-slug')) {
        $distinct = 'DISTINCT custom_column';
    }
    return $distinct;
}
add_filter('posts_distinct_request', 'modify_distinct_for_category', 10, 2);

Modify DISTINCT Clause Based on Search Query

Modify the DISTINCT clause only for search results.

function modify_distinct_for_search($distinct, $query) {
    if ($query->is_search()) {
        $distinct = 'DISTINCT custom_column';
    }
    return $distinct;
}
add_filter('posts_distinct_request', 'modify_distinct_for_search', 10, 2);