From 8c79957e33d1e5a70ac953763ef705cd90a8cfbb Mon Sep 17 00:00:00 2001 From: Matth_eu Date: Thu, 21 Nov 2013 10:28:26 +0000 Subject: [PATCH] Fix orderby lost in merge --- custom-meta-boxes.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/custom-meta-boxes.php b/custom-meta-boxes.php index 5f109ba6..da7184ec 100755 --- a/custom-meta-boxes.php +++ b/custom-meta-boxes.php @@ -128,3 +128,41 @@ function _cmb_field_class_for_type( $type ) { return false; } + +/** + * For the order of repeatable fields to be guaranteed, orderby meta_id needs to be set. + * Note usermeta has a different meta_id column name. + * + * TODO + * This is far from ideal as we are doing this on EVERY SINGLE QUERY. + * But... no other way to modify this query, or re-order in PHP. + * There is a trac ticket + patch that will fix this. http://core.trac.wordpress.org/ticket/25511 + * + * @param string $query + * @return string $query + */ +function cmb_fix_meta_query_order($query) { + + $pattern = '/^SELECT (post_id|user_id), meta_key, meta_value FROM \w* WHERE post_id IN \([\d|,]*\)$/'; + + if ( + 0 === strpos( $query, "SELECT post_id, meta_key, meta_value" ) && + preg_match( $pattern, $query, $matches ) + ) { + + if ( isset( $matches[1] ) && 'user_id' == $matches[1] ) + $meta_id_column = 'umeta_id'; + else + $meta_id_column = 'meta_id'; + + $meta_query_orderby = ' ORDER BY ' . $meta_id_column; + + if ( false === strpos( $query, $meta_query_orderby ) ) + $query .= $meta_query_orderby; + + } + + return $query; + +} +add_filter( 'query', 'cmb_fix_meta_query_order', 1 ); \ No newline at end of file