微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Wordpress 使用下拉菜单按日期和标题对帖子进行排序

如何解决Wordpress 使用下拉菜单按日期和标题对帖子进行排序

我正在尝试设置一个下拉菜单,将我的帖子按最新到​​最旧和按字母顺序排序。 这是我目前所拥有的:

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

这部分不起作用

<?PHP> $order = ''; ?>

<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>
</form>

并声明我在其中传递变量 'orderby' => $order

查询

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

$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;?>

我怎样才能做到这一点?

预先感谢您的帮助!

解决方法

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

<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'] 选择了哪个选项。然后根据返回的值,您可以设置自定义查询!所以您的自定义查询将是这样的:

$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','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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。