我正在尝试构建一个查询,以便按照日期自定义字段对一些帖子进行排序,其中日期的格式为dd/mm/yyyy。
它通过直接使用get_results
如本例所示:
$querystr = "
SELECT *
FROM wp_posts, wp_postmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = \'my_cutom_date\'
AND wp_posts.post_status = \'publish\'
AND wp_posts.post_type = \'post\'
ORDER BY STR_TO_DATE(wp_postmeta.meta_value, \'%d/%m/%Y\') ASC
";
但是,我想将这种行为转换为
WP_Query
, 使用
posts_where
滤器我做到了这一点:
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 10,
\'meta_key\' => \'my_custom_date\'
);
function filter_orderby( $orderby = \'\' ) {
global $wpdb;
$orderby .= " ORDER BY STR_TO_DATE($wpdb->postmeta.meta_value, \'%d/%m/%Y\') ASC ";
return $orderby;
}
add_filter( \'posts_orderby\', \'filter_orderby\' );
但它似乎没有返回任何东西。我错过了什么?
最合适的回答,由SO网友:Jan Fabry 整理而成
过滤器打开posts_orderby
应返回不以开头的字符串ORDER BY
, WordPresswill add that itself.
默认情况下,WordPress将按post_date
. 如果你不想那样,你应该overwrite order子句,而不是附加到它。因此,您的过滤器应如下所示:
function filter_orderby( $orderby ) {
global $wpdb;
return " STR_TO_DATE({$wpdb->postmeta}.meta_value, \'%d/%m/%Y\') ASC ";
}