我想为我的帖子制作一个筛选列表(在主页、搜索页面和归档页面中),这是我正在寻找的一个示例
排序方式:-日期(/?orderby=Date)-随机(/?orderby=rand)-视图(这里我需要一个orderby=视图或类似的东西)
我正在使用以下代码计算和查看帖子视图:
// Count views
function setPostViews($postID) {
$count_key = \'post_views_count\';
$count = get_post_meta($postID, $count_key, true);
if($count==\'\') {
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, \'0\');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
// Show views
function getPostViews($postID) {
$count_key = \'post_views_count\';
$count = get_post_meta($postID, $count_key, true);
if($count==\'\') {
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, \'0\');
return "0 View";
}
return $count.\' Views\';
}
// Show views in WP-Admin
add_filter(\'manage_posts_columns\', \'posts_column_views\');
add_action(\'manage_posts_custom_column\', \'posts_custom_column_views\', 5, 2);
function posts_column_views($defaults) {
$defaults[\'post_views\'] = __(\'Views\');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === \'post_views\') {
echo getPostViews(get_the_ID());
}
}
这可能吗?
最合适的回答,由SO网友:Johansson 整理而成
您可以使用元键按视图编号对查询进行排序:
$query = new WP_Query(
array(
\'meta_key\' => \'post_views_count\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\',
)
);
这将根据视图查询您的帖子。你可以改变
DESC
到
ASC
或
RAND
实现你的要求。
要使其在实际中发挥作用,您可以使用pre_get_posts()
筛选查询。在主题中使用此片段代码functions.php
文件:
add_action( \'pre_get_posts\', \'my_view_filter\' );
function my_view_filter($query){
if (
!is_admin() &&
$query->is_main_query() &&
( $query->is_home() || $query->is_archive() || $query->is_search() )
) {
if (isset($_REQUEST[\'orderby\'])) {
$order = $_REQUEST[\'orderby\'];
}
if ( $order === \'views\') {
$query->set(\'meta_key\', \'post_views_count\');
$query->set(\'orderby\', \'meta_value_num\');
$query->set(\'order\', \'DESC\');
}
}
}
现在,每当你访问
http://example.com/?orderby=views
, 您的帖子将按视图数过滤(降序,您可以将其更改为任何您想要的内容)