最好的方法可能是:
global $wpdb;
$count = $wpdb->get_row("SELECT COUNT(*) AS THE_COUNT FROM $wpdb->postmeta WHERE (meta_key = \'color\' AND meta_value = \'blue\')");
return $count->THE_COUNT;
以下是一系列函数,使其更易于使用:
/**
* Returns the number of posts a particular metakey is used for.
* Optionally qualified by a specific value or values in an array of the meta key.
*
* @param string $key
* @param null|string|array $value
*
* @return mixed
*/
function get_meta_count( $key, $value = null) {
global $wpdb;
$where = get_meta_where($key, $value);
$count = $wpdb->get_row("SELECT COUNT(*) AS THE_COUNT FROM $wpdb->postmeta WHERE $where");
return $count->THE_COUNT;
}
/**
* Returns the postmeta records for a particular metakey.
* Optionally qualified by a specific value or values in an array of the meta key.
*
* @param string $key
* @param null|string|array $value
*
* @return mixed
*/
function get_meta ( $key, $value = null) {
global $wpdb;
$where = get_meta_where($key, $value);
return $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE $where");
}
/**
* Returns the where string for a metakey query
*
* @param string $key
* @param null|string|array $value
*
* @return string
*/
function get_meta_where( $key, $value) {
$where = "meta_key = \'$key\'";
if (null !== $value) {
if (\\is_array($value)) {
\\array_walk($value,\'add_quote\');
$in = \\implode(\',\', $value); // Seperate values with a comma
$where .= " AND meta_value IN ($in)";
} else {
$where .= " AND meta_value = \'$value\'";
}
}
return $where;
}
/**
* Puts quotes around each value in an array when used as a callback function
*
* @param $value
* @param $key
*/
function add_quote( &$value, $key)
{
$value = "\'$value\'";
}