Skip to content

Instantly share code, notes, and snippets.

@johnciacia
Last active November 15, 2016 05:51
Show Gist options
  • Save johnciacia/a91e5d931653e76551ae3e2e8252e27b to your computer and use it in GitHub Desktop.
Save johnciacia/a91e5d931653e76551ae3e2e8252e27b to your computer and use it in GitHub Desktop.
Untested: convert author_name query to a tax query for co-authors-plus
<?php
add_action( 'rest_api_init', function() {
global $coauthors_plus;
if ( ! method_exists( $coauthors_plus, 'get_coauthor_by' ) ) {
return;
}
// When using co-authors-plus, convert author queries to tax queries
add_action( 'rest_post_query', function( $args ) use ( $coauthors_plus ) {
if ( ! isset( $args['es'] ) || true != $args['es'] ) {
return $args;
}
$authors = [];
if ( isset( $args['author__in'] ) ) {
$author_ids = $args['author__in'];
$args['author__in'] = [];
foreach ( $author_ids as $author_id ) {
$author = $coauthors_plus->get_coauthor_by( 'id', $author_id );
if ( is_a( $author, 'WP_User' ) ) {
$args['author__in'][] = (int) $author;
} else {
if ( isset( $author->ID ) ) {
$author = get_the_terms( $author->ID, 'author' );
$author = wp_list_pluck( $author, 'term_id' );
$authors = array_merge( $author, $authors );
}
}
}
}
if ( isset( $args['author_name'] ) ) {
$author = $coauthors_plus->get_coauthor_by( 'user_nicename', $args['author_name'] );
if ( is_a( $author, 'WP_User' ) ) {
$args['author_name'] = sanitize_user( $args['author_name'] );
} else {
if ( isset( $author->ID ) ) {
$author = get_the_terms( $author->ID, 'author' );
$author = wp_list_pluck( $author, 'term_id' );
$authors = array_merge( $author, $authors );
}
}
}
if ( ! empty( $authors ) ) {
$tax_query = [
'taxonomy' => 'author',
'field' => 'term_id',
'terms' => $authors,
'include_children' => false,
];
if ( empty( $args['tax_query'] ) ) {
$args['tax_query'] = [
$tax_query,
];
} else {
$args['tax_query'] = [
'relation' => 'AND',
$tax_query,
$args['tax_query']
];
}
}
return $args;
}, PHP_INT_MAX );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment