我需要允许在某些类别中进行后期订购。排序选项之一是自定义字段元值。第一个问题是,并不是所有的帖子都分配了那个meta,我需要按日期(默认)排序。
另一个问题是元字段应该使用ASC order和rest DESC。
到目前为止我的代码
在模板文件中:
$request = $_REQUEST;
global $query_string;
parse_str( $query_string, $qs_arr );
switch ( $request[\'sort\'] ) {
case \'title\':
$qs_arr[\'orderby\'] = \'title\';
$qs_arr[\'order\'] = \'ASC\';
break;
case \'publisher\':
$qs_arr[\'meta_key\'] = \'discography_publisher\';
$qs_arr[\'orderby\'] = \'meta_value\';
add_filter( \'posts_orderby\', \'sort_posts_orderby\' );
add_filter( \'get_meta_sql\', \'sort_get_meta_sql\' );
add_filter( \'posts_where\' , \'sort_posts_where\' );
break;
}
if ( isset( $request[\'sort\'] ) ) { query_posts( $qs_arr ); }
功能。php
function sort_get_meta_sql( $meta_sql ) {
$meta_sql[\'join\'] = " LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = \'discography_publisher\') ";
return $meta_sql;
}
function sort_posts_where( $where ) {
//here i remove the last statement "wp_postmeta.meta_key = \'discography_publisher\' " so query return all posts in category
$explode = explode( \'AND\', $where );
array_pop( $explode );
return implode( \'AND\', $explode );
}
function sort_posts_orderby( $orderby ) {
$orderby = \'COALESCE(wp_postmeta.meta_value, wp_posts.post_date) DESC\';
return $orderby;
}