[英]Wordpress sorting posts by date and title using a dropdown
我正在嘗試設置一個下拉列表,按最新到最舊和按字母順序對我的帖子進行排序。 這是我到目前為止所擁有的:
我聲明了一個空變量,然后是一個表單,我可以在其中更改這個空變量的內容。
這部分不起作用
<?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',
'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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.