我想用$wpdb->get_results
检索包含自定义字段的所有帖子的数组。我可以检索meta\\u key和meta\\u value列,如下所示:
[meta_key] => state [meta_value] => california
但我试图在对象中列出它们,如下所示:
[meta_key] => meta_value [state] => california [city] => san francisco
查询:
global $wpdb;
$query = "
SELECT ID, post_date, post_title, post_content, guid, meta_key, meta_value
FROM wp_posts INNER JOIN wp_postmeta
ON (wp_posts.ID = wp_postmeta.post_id)
";
$results = $wpdb->get_results($query);
foreach($results as $result) {
print_r($result);
}
是否可以使用别名和/或子查询来实现此目的?
SELECT ID, post_date, post_title, post_content, guid, meta_value AS (subquery here??)
SO网友:kaiser
注意,在继续之前:注意可移植性和安全性:
function wpse50056_get_post_meta()
{
global $wpdb;
$results = $wpdb->get_results( "
SELECT
ID,
post_date,
post_title,
post_content,
meta_key,
meta_value
FROM {$wpdb->posts}
INNER JOIN {$wpdb->postmeta}
ON ( $wpdb->posts.ID = {$wpdb->postmeta}.post_id )
" );
foreach( $results as $result )
{
printf( \'<pre>%s</pre>\', htmlspecialchars( var_export( $result, true ) ) );
}
}
add_action( \'shutdown\', \'wpse50056_get_post_meta\' );
SO网友:Larzan
为了清楚起见,为了不获取benhass所说的额外引用(我仍然使用kaiser和WP 3.7.1提供的代码获取它们),根本不要使用prepare方法(在这种情况下可以,因为我们只使用$wpdb对象本身提供的参数):
function wpse50056_get_post_meta() {
global $wpdb;
$query =
" SELECT
ID,
post_date,
post_title,
post_content,
meta_key,
meta_value
FROM $wpdb->posts
INNER JOIN $wpdb->postmeta
ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id)
";
$results = $wpdb->get_results( $query );
foreach( $results as $result ) {
echo \'<pre>\'; print_r( $result ); echo \'</pre>\';
}
}
add_action( \'shutdown\', \'wpse50056_get_post_meta\' );
但当然,请记住,只要在查询中使用其他参数
$wpdb->prepare 建议防止SQL注入。