I’m using this function from this accepted answer, which gets all values for a custom field key (cross-post).
How could it be modified to allow an array of post statuses?
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) {
global $wpdb;
if( empty( $key ) )
return;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}
eg something like this (doesn’t work)
function get_meta_values( $key = '', $type = 'post', $status = array( 'publish', 'draft' ) ) {
global $wpdb;
if( empty( $key ) )
return;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", $key, $status, $type ) );
return $r;
}
Use the IN operator for arrays.
When using
$wpdb->prepare()
you don’t have to use quotes around the string placeholder%s
. The string placeholder will be quoted automatically.That’s also the reason why you have to take precautions when using
$wpdb->prepare()
with the IN operator if the array values are strings.This first example doesn’t use the placeholders for the post stati but inserts them (comma separated and quoted) in the query string directly
This second example converts the array with the method from this answer https://stackoverflow.com/a/10634225
Note: both examples should be coded more defensively (is_array() etc.) if used in production.
Just implode the passed array:
This allows you to pass
$status
as either a string, or an array.Instead of taking status as an array take it as a string in query like
This works, I’ve tested it.