我需要一些功能方面的帮助。我正在尝试创建一个可以动态排序的帖子页面,以显示用户希望看到的帖子
使用场景:
帖子中有 4 个标题 ei:标题 A、标题 B、标题 C 和标题 D。
标题 A = 卡拉莫回顾;
标题 B = 目的地:公主港;
标题 C = 免费往返机票可以让您看到的事情;
标题 D = 在菲律宾旅行时要记住的五件事;
现在我想按以下方式排序:
最多评论
最受关注
按字母顺序 - 升序
用户可以通过单击如下所示的按钮来更改页面顺序。

最简单的方法是使用查询字符串。
我假设您正在查看类别页面。
首先我们将按钮添加到类别页面
<a href="?sortby=comment>Sort by Comment</a>
<a href="?sortby=views>Sort by Views</a>
<a href="?sortby=alphabet>Alphabetical</a>
Run Code Online (Sandbox Code Playgroud)
这会向页面的 URL 添加一个查询字符串,现在我们将在类别页面的顶部添加以下代码:
<?php
if (array_key_exists("sortby", $_GET) === true)
{
$newQuery = sortIt($_GET['sortby']);
}
?>
Run Code Online (Sandbox Code Playgroud)
之后,我们将创建一个函数,在functions.php模板中为我们对帖子进行排序
由于我们有 3 种排序类型,因此我们可以使用 switch case 或 if-else 语句。我将在这里使用 if-else。
<?php
function sortIt($sortType)
{
global $wp_query;
$cat_ID = get_query_var('cat');
if (strcmp($sortType, 'comment') == 0 )
{
$newQuery = new WP_Query( array( 'orderby' => 'comment_count' , 'cat' => $cat_ID, 'posts_per_page' => '10') );
}
if (strcmp($sortType, 'views') == 0 )
{
$newQuery = new WP_Query( array( 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'order'=> 'DESC', 'cat' => $cat_ID, 'posts_per_page' => '10') );
}
if (strcmp($sortType, 'alphabetical') == 0 )
{
$newQuery = new WP_Query( array( 'orderby' => 'title' , 'cat' => $cat_ID, 'posts_per_page' => '10') );
}
return $newQuery;
}
?>
Run Code Online (Sandbox Code Playgroud)
Wordpress 没有原生视图计数,我使用了我在此处阅读的说明。
由于我们拥有所有必要的函数和变量,因此我们需要重写查询。
您将编辑循环,使其如下所示:
<?php if ( $newQuery->have_posts() ) : while ( $newQuery->have_posts() ) : $newQuery->the_post(); ?>
Run Code Online (Sandbox Code Playgroud)
就是这样 :)