Order By Custom Field Using Meta Key for Pricing
-
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!
- The topic ‘Order By Custom Field Using Meta Key for Pricing’ is closed to new replies.