Skip to content

Instantly share code, notes, and snippets.

@landbryo
Created October 16, 2023 18:07
Show Gist options
  • Save landbryo/e4710d9f052d447d1aca733233bc5192 to your computer and use it in GitHub Desktop.
Save landbryo/e4710d9f052d447d1aca733233bc5192 to your computer and use it in GitHub Desktop.
Filter posts SQL query to include additional authors.
<?php
/**
* Hooks
*
* @return void
*/
public function init() {
// Filter author query to include posts author was added to as an additional author.
add_filter( 'posts_where', [ $this, 'filter_where' ], 10, 2 );
add_filter( 'posts_join', [ $this, 'filter_join' ], 10, 2 );
add_filter( 'posts_groupby', [ $this, 'filter_groupby' ], 10, 2 );
}
/**
* Filters the WHERE clause of the author query.
* This is needed because a standard WP meta_query always uses AND instead of OR.
*
* @see WP_Meta_Query::get_sql_clauses()
*
* @param string $where The WHERE clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*
* @return string
*/
public function filter_where( $where, $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_author() ) {
global $wpdb;
$author_id = $query->get_queried_object_id();
// Add meta query for author ID pattern.
$where .= $wpdb->prepare( " OR $wpdb->postmeta.meta_key = 'additional_authors' AND $wpdb->postmeta.meta_value LIKE %s AND $wpdb->posts.post_status = 'publish'", "%d:$author_id;%" );
}
return $where;
}
/**
* Filters the JOIN clause of the author query.
*
* @param string $join The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*
* @return string
*/
public function filter_join( $join, $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_author() ) {
global $wpdb;
// Add the INNER JOIN required for the meta query.
$join = "INNER JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
}
return $join;
}
/**
* Filters the GROUP BY clause of the author query.
*
* @param string $groupby The GROUP BY clause of the query.
* @param WP_Query $query The WP_Query instance.
*
* @return string
*/
public function filter_groupby( $groupby, $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_author() ) {
global $wpdb;
// Add the needed GROUPBY clause to combine duplicate results from the meta query using a JOIN.
$groupby = "$wpdb->posts.ID";
}
return $groupby;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment