Using WordPress ‘posts_distinct’ PHP filter

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

Usage

add_filter('posts_distinct', 'my_custom_posts_distinct', 10, 2);
function my_custom_posts_distinct($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

Examples

Remove Duplicate Posts

To remove duplicate posts from your query result, modify the DISTINCT clause.

add_filter('posts_distinct', 'remove_duplicate_posts', 10, 2);
function remove_duplicate_posts($distinct, $query) {
    global $wpdb;
    $distinct = "DISTINCT {$wpdb->posts}.ID";
    return $distinct;
}

Modify the DISTINCT clause to show only featured posts.

add_filter('posts_distinct', 'show_featured_posts', 10, 2);
function show_featured_posts($distinct, $query) {
    global $wpdb;
    $distinct = "{$wpdb->posts}.ID, {$wpdb->postmeta}.meta_key";
    return $distinct;
}

Exclude Posts in a Specific Category

To exclude posts in a specific category, modify the DISTINCT clause.

add_filter('posts_distinct', 'exclude_specific_category', 10, 2);
function exclude_specific_category($distinct, $query) {
    global $wpdb;
    $distinct = "{$wpdb->posts}.ID NOT IN (SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = 5)";
    return $distinct;
}

Remove Duplicate Custom Post Types

To remove duplicate custom post types from your query result, modify the DISTINCT clause.

add_filter('posts_distinct', 'remove_duplicate_custom_post_types', 10, 2);
function remove_duplicate_custom_post_types($distinct, $query) {
    global $wpdb;
    $distinct = "DISTINCT {$wpdb->posts}.ID, {$wpdb->posts}.post_type";
    return $distinct;
}

Filter Posts by Custom Field Value

Modify the DISTINCT clause to filter posts by a custom field value.

add_filter('posts_distinct', 'filter_posts_by_custom_field', 10, 2);
function filter_posts_by_custom_field($distinct, $query) {
    global $wpdb;
    $distinct = "{$wpdb->posts}.ID, {$wpdb->postmeta}.meta_value";
    return $distinct;
}