使用下拉菜单按自定义字段值对帖子进行排序

时间:2014-10-21 作者:Doen Webontwerp

我试图按一个自定义字段值(称为price)对帖子进行排序。仅在自定义字段值中使用数字。我想,该网站的访问者可以排序的价格上使用下拉列表的职位。我搜索了一个插件,但没有找到。现在您找到以下代码:

<?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); ?>
但最后一个选择选项“prijs”不起作用。

谁能帮帮我吗?还是需要更多信息?

对不起,如果我的英语不完全正确的话。

2 个回复
SO网友:Ashok Kumar Nath

而不是query_posts 尝试使用WP_Queryhttp://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

这是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 );

SO网友:admcfajn

您需要添加meta_key 所以它知道要比较哪个元值的数量。

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

$order = "&order=ASC&meta_key=prijs&orderby=meta_value_num";
更多信息:Custom query with orderby meta_value of custom field

结束