How to properly sanitize/secure a WP Query coming from the front end

I have an element in my front end that looks like this:

<div class="infinite-scroll" data-query-args='{"post_type":"post","tax_query":[{"taxonomy":"category","field":"term_id","terms":62}]}'></div>

It’s a container for triggering an infinite scroll that I made. Since I want it to work with multiple queries and multiple front end situations, the simplest way to make it work was to put the JSON encoded WP query directly in the element and pass it back to the server when loading more posts.

This feels like a security issue to me, so what’s the right way to make sure this can’t be exploited? I’m not saving any of that string in the DB so I don’t see how I can make sure it’s secure.

If it’s an all around bad idea then I can restructure it, but I’d rather not since the queries can get a little more complex with tags, multiple categories, search terms, etc. The only proper alternative I can think of is a data- tag for each item in the query (data-post-type, data-tax-query, etc) but it’s a lot more work.

Thanks

Solutions Collecting From Web of "How to properly sanitize/secure a WP Query coming from the front end"

The only way to do this would be to whitelist the allowed arguments, being very careful to limit them so as not to introduce an DOS attack vector.

Having said that, this is not how most infinite scroll implementations are built, and you may have better results relying on the WP API rest api instead for those kinds of requests