• Josh

    (@modernspark)


    I looked everywhere for this, and I had to piece the information together to make it work for my circumstance. I think others may get some use out of this, so I wanted to post it.

    Situation: Need to order posts or a custom post type using custom fields, particularly for ordering by prices. This situation was for real estate using custom fields with prices in the thousands and millions.

    Problems: The posts wouldn’t order correctly because I used commas and dollar signs in the custom fields. When I removed these, I no longer had commas in the prices where I needed them (200100 instead of $200,100).

    Solution: In your custom fields, enter the prices without dollar signs or commas. Hard-code the dollar sign in the template and use the basic PHP number format to add commas automatically.

    Here’s the gist:

    <?php
    $args = array(
    'post_type' => 'your_post_type',
    'orderby' => 'meta_value_num',
    'meta_key' => 'price',
    'order' => 'DESC'
    );
    ?>

    In my template file for the post, I used this to get the custom field and show the price in the proper format:

    <?php $price = get_post_meta($post->ID, 'price', true);
    if ( $price ) { ?>
    Price: $<?php echo number_format($price ,",",",",","); ?>
    <?php } else {} ?>

    Hope this helps someone out there!

Viewing 2 replies - 1 through 2 (of 2 total)
  • That is very helpful and just what I was after. thank you!

    I had a similar problem and ended up using this:

    <?php setlocale(LC_MONETARY, 'de_CH'); //use whatever you want ?>
    <?php echo money_format('%.0i', $price); //format with no decimals ?>

    Hope it helps somebody!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Order By Custom Field Using Meta Key for Pricing’ is closed to new replies.