Custom query on option click

I’m trying to implement functionality on home page that displays latest posts.
On header of index page user has option to see latest posts (posts ordered by date DESC) and option to se most viewed posts (posts ordered by custom post meta field). Posts by date in DESC order are default theme query.
So I’ve added two links.
Also, I’ve created js file that registers click on that links and makes a json call to php function in functions.php.
That all works fine but here comes the problem.

I don’t know how to write custom function that will on option 2 change default query to meta fields order and on option 1 return the default query.
I have tried with pre_get_posts (add and remove action in my function), changing default query, adding a new query variable and resetting it but nothing seems to work and I’m a bit lost. Either I’m getting broken pagination or no data.

There isn’t any similar example on internet so I would appreciate any help.

Read more here:: Custom query on option click

Leave a Reply

Your email address will not be published. Required fields are marked *