将自定义查询转换为wp_Query

时间:2014-12-23 作者:Pragnesh Chauhan

我使用了ClassisPress主题

我的问题如下

 $querydetails = "
   SELECT wposts.*
   FROM $wpdb->posts wposts 
   INNER JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id 
   INNER JOIN $wpdb->term_relationships yprelation ON yprelation.object_id = wposts.ID
   INNER JOIN $wpdb->term_taxonomy wptaxonomy ON wptaxonomy.term_taxonomy_id = yprelation.term_taxonomy_id
   INNER JOIN $wpdb->terms wpterms ON wpterms.term_id = wptaxonomy.term_id
   WHERE wpostmeta.meta_key = \'event_date\'
   AND STR_TO_DATE(wpostmeta.meta_value, \'%d-%m-%Y %H:%i:%s\') >= NOW()
   AND (wposts.post_status = \'publish\' || wposts.post_status = \'pending\' || wposts.post_status = \'future\')
   AND wposts.post_type = \'ad_listing\'
   AND (wpterms.term_id = 5 OR wptaxonomy.parent = 5)
   ORDER BY STR_TO_DATE(wpostmeta.meta_value, \'%d-%m-%Y %H:%i\') LIMIT 0,10";
我想将此查询转换为wp\\U查询,我尝试了以下代码

    $args = array(
    \'post_type\' => \'ad_listing\',
    \'post_status\' => array(\'publish\', \'pending\', \'future\'),
    \'orderby\' => \'meta_value\',
    \'order\' => \'ASC\',
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'key\' => \'event_date\',
            \'value\' => date(\'Y-m-d H:i:s\'),
            \'type\' => \'date\',
            \'compare\' => \'>=\'
        )
    ),
    \'tax_query\' => array(
        \'relation\' => \'and\',
        array(
            \'taxonomy\' => \'ad_cat\',
            \'field\' => \'slug\',
            \'terms\' => \'event-2\'
        )
    )
);

$query = new WP_Query($args);
echo "Last SQL-Query: {$query->request}";
返回低于结果

SELECT SQL_CALC_FOUND_ROWS yp_posts.ID 
FROM yp_posts 
INNER JOIN yp_term_relationships ON (yp_posts.ID = yp_term_relationships.object_id) 
INNER JOIN yp_postmeta ON (yp_posts.ID = yp_postmeta.post_id) 
WHERE 1=1 
AND ( yp_term_relationships.term_taxonomy_id IN (581,541,547,544,545,546,548,550,572,585,599,607,616,619) ) 
AND yp_posts.post_type = \'events\' 
AND ((yp_posts.post_status = \'publish\' OR yp_posts.post_status = \'future\' OR yp_posts.post_status = \'pending\')) 
AND ( (yp_postmeta.meta_key = \'event_date\' 
    AND CAST(yp_postmeta.meta_value AS DATE) >= \'2014-12-24 04:30:01\') ) 
GROUP BY yp_posts.ID ORDER BY yp_posts.post_date ASC LIMIT 0, 10 
但没有得到预期的结果

唯一的问题是退货AND CAST(yp_postmeta.meta_value AS DATE) >= \'2014-12-24 04:30:01\') )
代替
AND STR_TO_DATE(wpostmeta.meta_value, \'%d-%m-%Y %H:%i:%s\') >= NOW()

请帮忙

1 个回复
SO网友:Bikram Pahi

你错过了meta_value 参数
您可以这样使用:

$today=date(\'Y-m-d\');
$args = array(
               \'numberposts\' => 10,
                \'post_type\' => \'events\',
                \'meta_key\' => \'event_date\',
                \'meta_value >=\' => $today
            );

            // get results
$the_query = new WP_Query( $args );

结束