Home › Forums › Support › Using generateblocks_query_loop_args to sort by post_views_count does not work
- This topic has 5 replies, 2 voices, and was last updated 3 years, 4 months ago by
David.
-
AuthorPosts
-
November 24, 2022 at 3:21 am #2430716
Elvis
Hello,
I am trying to get the thing from title to work. Here is my gist. You can see it consistes of two files, one that sets the logic and another is a modified single.php file that runs the view counter (line 36).
In the logic file, I set the counter, and add it also as a column in the admin.
Then I try to modify the query block. And it does not work.For testing purpose I have tried to apply sorting using pre_get_posts at the bottom, and when I set homepage as recent posts, and activate the pre_get_posts it works perfect. But I need this to work on select query blocks. But no luck. What am I doing wrong?
Thanks
November 24, 2022 at 3:41 am #2430752David
StaffCustomer SupportHi there,
try changing the orderby to declare its a numeric value ie.
'orderby' => 'meta_value_num',November 24, 2022 at 8:33 am #2431511Elvis
Thanks David,
amazing, can you explain this modification please?Ordering is working now, there is one interesting thing though.
Posts with no views (zero) do not show at all.
What would be the way to show also them (zero view posts) only last?here is the function now:
function gb_query_by_views( $query_args, $attributes ) { if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'order_by_views' ) !== false ) { $query_args['post_type'] = 'post'; $custom_args = array( 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); } else { return $query_args; } return array_merge( $query_args, $custom_args ); } add_filter( 'generateblocks_query_loop_args', 'gb_query_by_views', 10, 2 );Thanks a lot.
November 24, 2022 at 8:42 am #2431525David
StaffCustomer SupportThe
meta_valuewould return the value as a string with alphabetical sorting.meta_value_numtells WP to treat the meta key value as a numeric value with number sorting.Try setting your
$count = 0;to$count = 1;– so all posts have at least one view.November 24, 2022 at 8:44 am #2431530Elvis
Thanks man. This is pretty sweet. 😀
November 25, 2022 at 3:33 am #2432656David
StaffCustomer SupportAwesome – glad to be of help 🙂
-
AuthorPosts
- You must be logged in to reply to this topic.