Select box, sort order of posts with custom fields and custom post type in Wordpress?

I want a select box that allows users to pick the order of posts displayed. (Like youtube order by date / relevance)

I'm displaying a list of custom post types (products). I want users to be able to select the order by price & size. (these are both custom fields).

I've written this code which allows me to change the order by changing the default variables below.

// Default variables
$post_type = 'products';
$custom_field = 'size';
$order = ASC; // ASC or DESC

// Find all matching posts in wordpress database
$querystr = "
  SELECT $wpdb->posts.* 
  FROM $wpdb->posts, $wpdb->postmeta
  WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
  AND $wpdb->posts.post_status = 'publish'
  AND $wpdb->posts.post_type = '$post_type'
  AND $wpdb->postmeta.meta_key = '$custom_field' 
  ORDER BY $wpdb->postmeta.meta_value $order
";

// Get all the posts
$pageposts = $wpdb->get_results($querystr, OBJECT);

I now need to let public change the default variables with a select box, but I don't know how.

<form method="post">
  <select name="custom_field_choice">
    <option value="size">Size</option>      
    <option value="price">Price</option>
  </select>
  <input type="submit" value="order_select" />
</form>

Is it possible to allow a user to change a php variable with a select box? If not, whats the best way to do this?

Answers


Try to change your code to receive variable from http post request like this

// Default variables
$post_type = 'products';
$custom_field = 'size';
$order = ASC; // ASC or DESC
$orderField = $post->custom_field_choice;

// Find all matching posts in wordpress database
$querystr = "
  SELECT $wpdb->posts.* 
  FROM $wpdb->posts, $wpdb->postmeta
  WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
  AND $wpdb->posts.post_status = 'publish'
  AND $wpdb->posts.post_type = '$post_type'
  AND $wpdb->postmeta.meta_key = '$custom_field' 
  ORDER BY $orderField $order
";

// Get all the posts
$pageposts = $wpdb->get_results($querystr, OBJECT);

Option's values size and price must be column name on your database table.


Need Your Help

Can't find Vector in Windows store app

xaml windows-store-apps winrt-xaml data-visualization

I can't find Vector class in Windows store app. I understand this is available in WPF but can I find a similar custom implementation in Windows store app.

Can I access an encrypted SQL Server Compact database in Excel VBA?

sql excel excel-vba connection-string compact-database vba

I want to access an encrypted SQL Server Compact Edition database via VBA. I can access the database fine when it is not encrypted, but the code breaks when I try to use a password: