我一直在使用自定义查询从自定义帖子类型(dabg_events)中提取具有特定类别(“婚礼事件”或term_taxonomy_id ='4')的日期订购帖子。
$querystr = "SELECT DISTINCT wp_posts. *
FROM wp_postmeta, wp_posts
LEFT JOIN wp_term_relationships ON ( wp_posts.ID = wp_term_relationships.object_id )
WHERE wp_term_relationships.term_taxonomy_id = '4'
AND wp_posts.ID = wp_postmeta.post_id
AND (wp_postmeta.meta_key = '_dabg-event-start-date' AND STR_TO_DATE(wp_postmeta.meta_value, '%m/%d/%Y' ) >= CURDATE( )
OR wp_postmeta.meta_key = '_dabg-event-end-date' AND STR_TO_DATE( wp_postmeta.meta_value, '%m/%d/%Y' ) >= CURDATE( ) )
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'dabg_events'
ORDER BY STR_TO_DATE( wp_postmeta.meta_value, '%m/%d/%Y' ) ASC";
$events = $wpdb->get_results($querystr, OBJECT);
这样可以获得我需要的帖子。现在我需要找到min(_dabg-event-start-date)和max(_dabg-event-start-date)。我的问题有两个部分。 1.有没有更简单的方法来查询我正在寻找的帖子类型?或2.如何修改此查询以获取min(_dabg-event-start-date)和max(_dabg-event-start-date)?
答案 0 :(得分:0)
这样的事情应该做你想要的。这是未经测试的,因为我没有任何与您匹配的数据。它会返回日期,而不是字符串 - 如果您需要将结果作为字符串,则需要进行转换。
SELECT min(STR_TO_DATE(s.meta_value, '%m/%d/%Y' )) as min_start_date,
max(STR_TO_DATE(s.meta_value, '%m/%d/%Y' )) as max_start_date
FROM wp_posts p
LEFT JOIN wp_postmeta s ON p.ID = s.post_id AND s.meta_key = '_dabg-event-start-date'
LEFT JOIN wp_postmeta e ON p.ID = e.post_id AND e.meta_key = '_dabg-event-end-date'
JOIN wp_term_relationships ON p.ID = wp_term_relationships.object_id
WHERE wp_term_relationships.term_taxonomy_id = '4'
AND ( STR_TO_DATE(s.meta_value, '%m/%d/%Y' ) >= CURDATE() OR STR_TO_DATE( e.meta_value, '%m/%d/%Y' ) >= CURDATE() )
AND p.post_status = 'publish'
AND p.post_type = 'dabg_events'
我无法将max
和min
添加到您的查询中,因为这可能会拉回最大结束日期而不是您需要的开始日期。