1

I'm trying to sort my posts by a custom field value, called price. Only using numbers in the custom field value. I want that the visitors of the website can sort the posts on price by using a dropdown. I searched for a plugin, but couldn't found that. Now u found the code below:

<?php
  $order = "&order=DESC";
  if ($_POST['select'] == 'tag') { $order = "&tag=mytag";  }
  if ($_POST['select'] == 'title') { $order = "&order=ASC&orderby=title";  }
  if ($_POST['select'] == 'newest') { $order = "&order=DESC"; }
  if ($_POST['select'] == 'oldest') { $order = "&order=ASC";  }
  if ($_POST['select'] == 'mcommented') { $order = "&order=DESC&orderby=comment_count";  }
  if ($_POST['select'] == 'lcommented') { $order = "&order=ASC&orderby=comment_count";  }
  if ($_POST['select'] == 'prijs') { $order = "&order=ASC&orderby=meta_value_num";  }
?>
<form method="post" id="order">
  Sort reviews by:
  <select name="select" onchange='this.form.submit()'>
    <option value="tag"<?php selected( $_POST['select'],'tag', 1 ); ?>>Tag</option>
    <option value="title"<?php selected( $_POST['select'],'title', 1 ); ?>>Title</option>
    <option value="newest"<?php selected( $_POST['select'],'newest', 1 ); ?>>Newest</option>
    <option value="oldest"<?php selected( $_POST['select'], 'oldest', 1 ); ?>>Oldest</option>
    <option value="mcommented"<?php selected( $_POST['select'],'mcommented', 1 ); ?>>Most commented</option>
    <option value="lcommented"<?php selected( $_POST['select'],'lcommented' , 1 ); ?>>least commented</option>
    <option value="prijs"<?php selected( $_POST['select'],'prijs' , 1 ); ?>>prijs</option>
  </select>
</form>
<?php query_posts($query_string . $order); ?>

But the last selection option 'prijs' is not working.

Can somebody help me? Or do you need more information?

Sorry for my English if it's not totaly correct.

1

Instead of query_posts try using WP_Query class. http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

This is example from codex:

$args = array(
'post_type'  => 'my_custom_post_type',
'meta_key'   => 'age',
'orderby'    => 'meta_value_num',
'order'      => 'ASC',
'meta_query' => array(
    array(
        'key'     => 'age',
        'value'   => array( 3, 4 ),
        'compare' => 'IN',
    ),
),
);
$query = new WP_Query( $args );
| improve this answer | |
0

You need to add meta_key so it knows which meta value to compare the numbers of.

https://codex.wordpress.org/Class_Reference/WP_Meta_Query

$order = "&order=ASC&meta_key=prijs&orderby=meta_value_num";

More info: Custom query with orderby meta_value of custom field

| 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.