Wordpress Custom Query String
I have a meta field called date & I need to query all records where that timestamp is equal to or less than today...
<?php
$time = time();
$querystr = "
SELECT wposts.*
FROM $wpdb->post开发者_如何学Cs wposts, $wpdb->postmeta wpostmeta
WHERE wpostmeta.meta_key = 'date'
AND wpostmeta.meta_value <= $time
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
You could try something like this :
$today = date('Y-m-d');
$querystr = "
SELECT *
FROM wp_posts, wp_postmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = 'date'
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
AND STR_TO_DATE(wp_postmeta.meta_value, '%Y/%m/%d') <= '$today'
ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%Y/%m/%d') ASC
";
$custom_loop = $wpdb->get_results($querystr, OBJECT);
In the last two lines of the que query, you have to specify the format of your date (in your custom field "date"). For example if your custom "date" field has a dd/mm/YYYY format you would use :
AND STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') <= '$today'
ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') ASC
The $today
date has to be Y-m-d
because it's the default time format, used for the comparison by mysql.
精彩评论