0

I'm trying to sort my WP_Query by a meta key but the problem is that the meta key is a string and not a number. What i want to do is somehow remove the letters from the string and then order by this value.

For example, 'meta_key' contains letters before the number like FOR04. Is it possible to somehow remove the letters from this within the $args?

Can i do something like this?

'meta_key' => preg_replace('/[^0-9]+/', 'test_2')   


  $args = array(
            'post_type' => 'property',
            'meta_query' => array(
                  array(
                    'key' => 'test_1',
                    'value' => $post->ID,
                    'compare' => 'IN',
                  ),
          ),
                  'meta_key' => 'test_2',
                  'orderby' => 'meta_value_num',
                  'posts_per_page' => -1
          );

I've tried this method but it's not sorting them correctly..

  $args['meta_key'] = preg_replace('/[^0-9]+/', '', 'db-id');
            $args = array(
            'post_type' => 'property',
            'meta_query' => array(
                  array(
                    'key' => 'court',
                    'value' => $post->ID,
                    'compare' => 'IN',
                  ),
          ),
                  'orderby' => 'meta_value_num',
                  'order' => 'DESC',
                  'posts_per_page' => -1
          );
Shaun
  • 757
  • 1
  • 8
  • 36
  • Use `$args['meta_key'] = preg_replace('/[^0-9]+/', '', $args['meta_key'])` – Mohammad Nov 16 '18 at 15:29
  • Hi Mohammad, thanks for your help! So do i need to change anything in the above or will the code you've given me pick up on the meta_key 'test_2' ? – Shaun Nov 16 '18 at 15:31
  • The code remove letters from `meta_key` – Mohammad Nov 16 '18 at 15:42
  • Do i add it like this? $args['meta_key'] = preg_replace('/[^0-9]+/', '', test_2) – Shaun Nov 16 '18 at 15:49
  • If value of `meta_key` always is `test_2`, you can use it. Note that the **test_2** should wrapped in quote – Mohammad Nov 16 '18 at 15:51
  • Hi Mohammad, i've added the code you suggested but it's not sorting it correctly. Do i need to turn the string into a INT? See edited question – Shaun Nov 16 '18 at 15:58
  • My code only remove letters from target string. You should use sorting functions for your purpose – Mohammad Nov 16 '18 at 16:00
  • Thanks Modammad, Can you point me in the direction of this please? – Shaun Nov 16 '18 at 16:03
  • Check [Sort Multi-dimensional Array by Value](https://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Mohammad Nov 16 '18 at 16:06

0 Answers0