简体   繁体   中英

Get posts by Wordpress user display name via MySQL query

I have a search form in Wordpress that searches all posts titles, content, and custom fields in a custom post type. It won't search by author though. I'd like if the search keyword matches a display name to go ahead and also output any posts by that author.

Here's my current code (the display_name part of it is obviously wrong, but illustrates what I want to accomplish). Everything works except for the get posts by display_name part. Any help or guidance is appreciated :)

// Code originally modified 
// from http://www.deluxeblogtips.com/2012/04/search-all-custom-fields.html

global $wpdb;
// Gets the ?crs= search from the submitted form
$keyword = sanitize_text_field( $_GET['crs'] );
$keyword = '%' . like_escape( $keyword ) . '%'; 

// Search in all custom fields
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
    SELECT DISTINCT post_id FROM {$wpdb->postmeta}
    WHERE meta_value LIKE '%s'
", $keyword ) );

// Search in post_title and post_content
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
    SELECT DISTINCT ID FROM {$wpdb->posts}
    WHERE post_title LIKE '%s'
    OR post_content LIKE '%s'
", $keyword, $keyword ) );

// Search in User Table for Display Name
// This is where I'm not sure what how to get the posts by display_name
$post_ids_user = $wpdb->get_col( $wpdb->prepare( "
    SELECT DISTINCT post_id FROM {$wpdb->users}
    WHERE display_name LIKE '%s'
", $keyword ) );

$post_ids = array_merge( $post_ids_meta, $post_ids_post, $post_ids_user );

// Query arguments for WP_Query
$args = array(
    'post_type'   => 'courses',
    'post_status' => 'publish',
    'limit' => '',
    'post__in'    => $post_ids,
);

One thing i would like to suggest instead of running multiple queries join your tables and work around in a go

SELECT DISTINCT post_id FROM {$wpdb->users} WHERE display_name LIKE '%s' this is wrong query you cannot get the post ids from users table ,relation of posts and user is maintained in the posts table and each post contains user id in post_author column

Try this one

$post_ids = $wpdb->get_col( $wpdb->prepare( "
    SELECT p.ID FROM $wpdb->posts p
INNER JOIN $wpdb->users u ON (p.`post_author` = u.`ID`)
LEFT JOIN $wpdb->postmeta m ON (p.`ID`= m.`post_id`)
WHERE ( u.display_name LIKE '%s' OR p.post_title LIKE '%s' 
OR p.post_content LIKE '%s' OR m.meta_value LIKE '%s')
GROUP BY p.`ID`
", $keyword ) );

//print_r($post_ids); //you will get the post ids
$post_ids=array_values(array_unique($post_ids));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM