Wordpress 使用下拉菜单按日期和标题对帖子进行排序 [英] Wordpress sorting posts by date and title using a dropdown

查看:24
本文介绍了Wordpress 使用下拉菜单按日期和标题对帖子进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个 下拉,它将按最新到最旧和按字母顺序对我的帖子进行排序.

I'm trying to set up a drop-down that would sort my posts by Newest to oldest and Alphabetical.

这是我目前所拥有的:

我声明了一个空变量,然后是一个表单,我可以在其中更改这个空变量的内容.

I'm declaring an empty variable, then a form where I can change the contents of this empty variable.

这部分不起作用

<form method="GET">
  <select name="orderby" id="orderby">
    <option value="<?php echo ($order = 'date'); ?>">Newest to Oldest</option>
    <option value="<?php echo ($order = 'title'); ?>">Alphabetical</option>
    <button type="submit">Apply</button>
  </select>
</form>

并声明我传递变量 'orderby' => 的查询$订单

这部分有效(我得到了所有帖子的列表,手动更改查询也有效)

$wpb_all_query = new WP_Query(array('post_type'=>'post', 'posts_per_page'=>-1, 'order'=>'ASC', 'orderby'=> $order)); ?>

if ( $wpb_all_query->have_posts() ) :
<ul>


<?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul>
<?php endif;?>

我怎样才能做到这一点?

How can I make this work?

预先感谢您的帮助!

推荐答案

所以你的 html 表单应该是这样的:

So you're html form would be something like this:

<form method="GET">
    <select name="orderby" id="orderby">
      <option value="date">Newest to Oldest</option>
      <option value="title">Alphabetical</option>
    </select>
    <button type="submit">Apply</button>
</form>

然后检查用户使用isset$_GET['orderby'] 选择了哪个选项.然后根据返回的值,您可以设置自定义查询!所以您的自定义查询将是这样的:

Then check which option, user selected using isset and $_GET['orderby']. Then based on the value returned, you could set your custom query! So your custom query would be something like this:

$custom_orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : "";

if(!empty($custom_orderby) && "title" == $custom_orderby):
  $custom_query = new WP_Query(array(
    'post_type'=>'post',
    'posts_per_page'=>-1,
    'orderby'=> "title",
    'order'=>'ASC',
    ));
endif;

if(!empty($custom_orderby) && "date" == $custom_orderby):
  $custom_query = new WP_Query(array(
    'post_type'=>'post',
    'posts_per_page'=>-1,
    'orderby'=> "date",
    'order'=>'DESC',
    ));
endif;?>

<ul>

<?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul>

这篇关于Wordpress 使用下拉菜单按日期和标题对帖子进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆