Including variables in a custom select statement in WordPress
My custom select statement:
$querystr = "
SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->comments
WHERE $wpdb->posts.ID = $wpdb->comments.comment_post_ID
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
GROUP BY $wpdb->posts.ID
ORDER BY comment_count DESC
";
My aim is to limit the results returned to a particular set of post authors.
I have an array of WordPress post author user IDs in a variable
$user_ids
.
I thought about adding the following to my select statement, but I'm sure the following syntax isn't the right way to do it:
AND $wpdb->posts.post_author = $user_ids
Hoping someone can help show me the right way to do this?
Solutions
if
$user_ids
are coma
separated values
then you can do this
AND $wpdb->posts.post_author in ( $user_ids)
if
$user_ids
is an array then use this :
AND $wpdb->posts.post_author in ( implode( ',', $user_ids ))
First you should make a string:
$user_ids_string = implode(',',$user_ids)
then your syntax will be:
AND $wpdb->posts.post_author in ($user_ids_string)
Note: If your ids are not integers you should also wrap them with quotes
''