我有一个自定义帖子类型“event”,一个自定义元字段“event_date”和一个自定义分类“locations”。
我想查询$wpdb
以这种方式检索帖子
帖子必须为“事件”帖子类型“事件”必须与特定$location
“位置”分类中的术语必须按“event\\u date”自定义元值(实际上是yymmdd
格式),与今天的当前日期相比,我尝试使用以下查询参数(我可以获得$location
值(ID或slug)正确,并传递到此查询):
SELECT $wpdb->posts.*
LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->terms.term_id = $location
AND $wpdb->term_taxonomy.taxonomy = \'locations\'
AND $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->posts.post_type = \'event\'
AND $wpdb->posts.post_status = \'publish\'
AND $wpdb->postmeta.meta_key = \'event_date\'
AND $wpdb->postmeta.meta_value > NOW()
ORDER BY $wpdb->postmeta.meta_value ASC
LIMIT $numberofposts
查询不工作;如果我删除了连接部分和分类部分,它将起作用,通过将“event\\u date”meta与
NOW()
日期
我想我在分类部分做得不对。。。
按照建议,我试着WP_Query
而不是$wpdb
查询:
$args = array(
\'post_type\' => \'event\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'locations\',
\'field\' => \'id\',
\'terms\' => $location // location term id
)
),
\'meta_key\' => \'event_date\', // this meta field stores event date in yymmdd format
\'meta_value\' => $today, // this would be today\'s date in yymmdd format
\'meta_compare\' => \'>=\',
\'posts_per_page\' => $numberofposts, // this variable stores the number of posts I want to get
\'orderby\' => \'meta_value_num\'
);
但是,在后一种情况下,查询将返回指定post\\u类型下的所有post,而不考虑
$args
包括排序顺序
我试过使用meta_query
而不是meta_key
但结果并没有改变
最合适的回答,由SO网友:Milo 整理而成
你的输入有误orderby
, 和meta_value_num
仅用作orderby
值,请尝试以下操作:
$args = array(
\'post_type\' => \'event\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'locations\',
\'field\' => \'id\',
\'terms\' => $location // location term id
)
),
\'meta_key\' => \'event_date\', // this meta field stores event date in yymmdd format
\'meta_value\' => $today, // this would be today\'s date in yymmdd format
\'meta_compare\' => \'>=\',
\'posts_per_page\' => $numberofposts, // this variable stores the number of posts I want to get
\'orderby\'=> \'meta_value_num\'
);