我想你需要一个过滤器posts_orderby
为此,请执行以下操作:
add_filter( \'posts_orderby\', function ( $orderby, $query ) {
if ( $query->get( \'orderby\' ) == \'zuk\' ) {
global $wpdb;
//$field = $wpdb->posts . \'.post_title\';
$field = $wpdb->postmeta . \'.meta_value\';
$order = $query->get( \'order\' );
$orderby = $wpdb->prepare(
\'CASE\'
. \' WHEN LEFT(\' . $field . \', 1) = %s THEN CONCAT(%s, LPAD(SUBSTR(\' . $field . \', 2), LENGTH(~0), %s))\'
. \' WHEN LEFT(\' . $field . \', 1) = %s THEN CONCAT(%s, LPAD(SUBSTR(\' . $field . \', 3), LENGTH(~0), %s))\'
. \' ELSE LPAD(\' . $field . \', LENGTH(~0), %s)\'
. \' END \' . $order
, \'Z\', \'A\', \'0\', \'U\', \'B\', \'0\', \'0\'
);
}
return $orderby;
}, 10, 2 );
$args = array(
\'meta_key\' => \'SKU\',
\'orderby\' => \'zuk\',
\'order\' => \'ASC\',
);
$query = new WP_Query( $args );
(如果数据的编号始终为5位数,则可以根据长度进行排序:
add_filter( \'posts_orderby\', function ( $orderby, $query ) {
if ( $query->get( \'orderby\' ) == \'zuk\' ) {
global $wpdb;
//$field = $wpdb->posts . \'.post_title\';
$field = $wpdb->postmeta . \'.meta_value\';
$order = $query->get( \'order\' );
$orderby = \'LENGTH(\' . $field . \') \' . $order . \', \' . $field . \' \' . $order;
}
return $orderby;
}, 10, 2 );
但这显然要脆弱得多。)