Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Emmanuele Massimi
Emmanuele Massimi
7,420 Points

New WP_Query from within plugin?

Hello All,

I am trying to create a plugin that sorts posts based on a drop down selection. However, I don't want my selection to affect the main query, but just the posts I would like to filter.

I am getting confused in regards to where and how I should create this new query, and since it should be enclosed in a plugin, I don't think editing a template is the best approach.

Am I even making sense?

Thank you very much for reading!

4 Answers

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

Hi, this is a tricky question. I'm not sure off the top of my head how you would automatically figure out what query someone is using on a given template. If you're only doing blog posts that helps simplify it since you can just run a basic WP_Query and change the sort and orderby parameters.

I think your best approach is to have the dropdown menu fire off an AJAX request to a function in your plugin file that does the query and returns the new post information, which you would the use to replace the results currently on the page.

Emmanuele Massimi
Emmanuele Massimi
7,420 Points

I'll have a look, thank you very much!

Emmanuele Massimi
Emmanuele Massimi
7,420 Points

Hello Zac,

Thanks for taking the time to reply. What you say makes a lot of sense to me.

Yes, I only want to filter a specific type of posts, and yes, it would make sense to use an AJAX request, however I am still unsure as to how to use the returned data. How would I use that to replace the results on the page? I don't mind doing my reading, so if you could just point me to the right direction that would be great too.

Thanks!