Skip to content
This repository has been archived by the owner. It is now read-only.

if searching by name, include all posts by that person #2

Merged
merged 1 commit into from Oct 18, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
61 changes: 46 additions & 15 deletions functions.php
Expand Up @@ -13,20 +13,6 @@ function my_search_query( $query ) {
}
add_action( 'pre_get_posts', 'my_search_query' );

//
// Order search results by post_title
//
function my_search_query( $query ) {
// not an admin page and is the main query
if ( !is_admin() && $query->is_main_query() ) {
if ( is_search() ) {
$query->set( 'orderby', 'post_title' );
$query->set( 'order', 'ASC' );
}
}
}
add_action( 'pre_get_posts', 'my_search_query' );

function neag_scripts() {
wp_enqueue_style( 'neag-style', get_stylesheet_directory_uri() . '/css/neag.css');
wp_enqueue_script('neag-custom', get_stylesheet_directory_uri().'/js/custom.js', array('jquery', 'cs'));
Expand Down Expand Up @@ -195,5 +181,50 @@ if(function_exists("register_field_group"))
'menu_order' => 0,
));
}

//==================================================
// include authors in search results
//==================================================
/**
* Include posts from authors in the search results where
* either their display name or user login matches the query string
*
* @author danielbachhuber
*/
add_filter( 'posts_search', 'db_filter_authors_search' );
function db_filter_authors_search( $posts_search ) {
// Don't modify the query at all if we're not on the search template
// or if the LIKE is empty
if ( !is_search() || empty( $posts_search ) )
return $posts_search;
global $wpdb;
// Get all of the users of the blog and see if the search query matches either
// the display name or the user login
add_filter( 'pre_user_query', 'db_filter_user_query' );
$search = sanitize_text_field( get_query_var( 's' ) );
$args = array(
'count_total' => false,
'search' => sprintf( '*%s*', $search ),
'search_fields' => array(
'display_name',
'user_login',
),
'fields' => 'ID',
);
$matching_users = get_users( $args );
remove_filter( 'pre_user_query', 'db_filter_user_query' );
// Don't modify the query if there aren't any matching users
if ( empty( $matching_users ) )
return $posts_search;
// Take a slightly different approach than core where we want all of the posts from these authors
$posts_search = str_replace( ')))', ")) OR ( {$wpdb->posts}.post_author IN (" . implode( ',', array_map( 'absint', $matching_users ) ) . ")))", $posts_search );
return $posts_search;
}
/**
* Modify get_users() to search display_name instead of user_nicename
*/
function db_filter_user_query( &$user_query ) {
if ( is_object( $user_query ) )
$user_query->query_where = str_replace( "user_nicename LIKE", "display_name LIKE", $user_query->query_where );
return $user_query;
}
?>