0

I have a meta box where a 'Case Result' CPT can be assigned a monetary value (e.g. $60 Million). I need to convert this into a decimal number for use as the meta_key in WP_Query.

I understand how to do the reverse (https://www.php.net/manual/en/function.number-format.php#89888), but want to know if there's a reasonable approach to taking a '$60 Million' string and converting it to '60000000'.

My current query is below, which is re-run across multiple 'Attorney' pages (hence the $attorney_name for terms) to show the only cases they were responsible for. I'd like to order these posts by their monetary value in descending order, but I'm aware the current config (meta_type etc) won't work with the value in it's current string state. Any advice would be massively appreciated.

    // Configure query
    $query = new WP_Query( array(
        'posts_per_page' => -1,
        'post_type' => 'case-result',
        'tax_query' => array(
            array (
                // Filter CPT's to display by taxonomy
                'field' => 'name',
                'taxonomy' => 'case-result-attorney',
                'terms' => $attorney_name,
            )
        ),
        // Sort CPT's by meta
        'meta_key' => 'case_claim_value',
        'meta_type' => 'NUMERIC',
        'order' => 'DESC',
        'orderby' => 'meta_value_num',
    ) );
  • Your post meta query appears to have been inserted in the middle of a tax query, is this a full code snippet or has it been cut in half? – Tom J Nowell Feb 2 at 21:28
  • Hey Tom - messed it up during formatting. Just updated the query – Graeme Bryson Feb 2 at 21:45
1

For decimal values, use DECIMAL as it says in the official WP_Query documentation:

‘meta_value‘ – Note that a ‘meta_key=keyname‘ must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). Use ‘meta_value_num‘ instead for numeric values. You may also specify ‘meta_type‘ if you want to cast the meta value as a specific type. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’, same as in ‘$meta_query‘. When using ‘meta_type’ you can also use ‘meta_value_*’ accordingly. For example, when using DATETIME as ‘meta_type’ you can use ‘meta_value_datetime’ to define order structure.

https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.