Skip to content

Instantly share code, notes, and snippets.

@boonebgorges
Created December 5, 2017 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boonebgorges/547b49e87acbe9d2af18812a1b6dcf04 to your computer and use it in GitHub Desktop.
Save boonebgorges/547b49e87acbe9d2af18812a1b6dcf04 to your computer and use it in GitHub Desktop.
Enable BuddyPress Docs search to match based on attachment filenames
<?php
/**
* This is not needed for BP Docs 2.1+. See https://github.com/boonebgorges/buddypress-docs/issues/592
*/
add_filter( 'bp_docs_pre_query_args', function( $args, BP_Docs_Query $query ) {
// For attachments, search separately and then append to WP's default search handling.
if ( bp_docs_enable_attachments() ) {
add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
$attachment_posts = get_posts( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
's' => $query->query_args['search_terms'],
) );
if ( $attachment_posts ) {
$GLOBALS['bp_docs_search_attachment_parents'] = wp_list_pluck( $attachment_posts, 'post_parent' );
add_filter( 'posts_search', 'bbg_attachment_filename_search_filter' );
}
}
return $args;
}, 10, 2 );
/**
* Filters post search to include Docs with attachments whose filename matches search term.
*
* @param string $search Search string, as generated by WP_Query.
* @return string Modified SQL clause.
*/
function bbg_attachment_filename_search_filter( $search ) {
global $wpdb, $bp_docs_search_attachment_parents;
remove_filter( 'posts_clauses', 'bbg_attachment_filename_search_filter' );
if ( ! $search || empty( $bp_docs_search_attachment_parents ) ) {
return $search;
}
$raw_search = preg_replace( '/^\s*AND/', '', $search );
$parent_ids = implode( ',', array_map( 'intval', $bp_docs_search_attachment_parents ) );
$search = " AND ( $wpdb->posts.ID IN ({$parent_ids}) OR $raw_search )";
return $search;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment