Using WordPress ‘posts_join_paged’ PHP filter

posts_join_paged is a WordPress PHP filter that allows you to modify the JOIN clause of a query, specifically for paging queries.

Usage

add_filter('posts_join_paged', 'custom_posts_join_paged', 10, 2);

function custom_posts_join_paged($join, $query) {
    // your custom code here
    return $join;
}

Parameters

  • $join (string) – The JOIN clause of the query.
  • $query (WP_Query) – The WP_Query instance (passed by reference).

More Information

See WordPress Developer Resources: posts_join_paged

Examples

Join custom table with post table

Join a custom table named wp_custom_data with the post table using the post_id field.

add_filter('posts_join_paged', 'join_custom_data_table', 10, 2);

function join_custom_data_table($join, $query) {
    global $wpdb;
    $join .= " LEFT JOIN {$wpdb->prefix}custom_data ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}custom_data.post_id";
    return $join;
}

Join post meta table for a specific meta key

Join the post meta table for the meta key special_feature.

add_filter('posts_join_paged', 'join_special_feature_meta', 10, 2);

function join_special_feature_meta($join, $query) {
    global $wpdb;
    $join .= " LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = 'special_feature'";
    return $join;
}

Exclude posts with specific term from custom taxonomy

Exclude posts with a term beginner from the custom taxonomy difficulty_level.

add_filter('posts_join_paged', 'exclude_beginner_posts', 10, 2);

function exclude_beginner_posts($join, $query) {
    global $wpdb;
    $join .= " LEFT JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id";
    $join .= " LEFT JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id";
    return $join;
}

Join user table to display author information

Join the user table to display author information like name and email.

add_filter('posts_join_paged', 'join_user_table', 10, 2);

function join_user_table($join, $query) {
    global $wpdb;
    $join .= " LEFT JOIN {$wpdb->users} ON {$wpdb->posts}.post_author = {$wpdb->users}.ID";
    return $join;
}

Join comment table to show comment count

Join the comment table to display the comment count for each post.

add_filter('posts_join_paged', 'join_comment_table', 10, 2);
function join_comment_table($join, $query) {
    global $wpdb;
    $join .= " LEFT JOIN {$wpdb->comments} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID";
    return $join;
}