0

I have the following code:

const FORMS = document.querySelectorAll(".search-form");

FORMS.forEach((form) => {
    const INPUT  = form.querySelector(".search-form__input");
    const BUTTON = form.querySelector(".search-form__button");

    BUTTON.addEventListener("click", (e) => {
        e.preventDefault();

        wp.apiRequest({
            path: "wp/v2/posts",
            data: {
                search: INPUT.value,
            },
        }).then(data => {
            console.log(data);
        });

    }, { passive: false });
});

WP_Query allows you to specify "fields" => "ids" to return only the post IDs. I only need the IDs from this request, so in order to cut down on database queries, I'd like to apply this same setting to the request. Is there a way to specify this in the REST API? I've tried setting fields: "ids", in the data property, but that doesn't have any effect.

5
  • Does _fields : "id" work?
    – birgire
    Jun 21 at 17:45
  • Maybe create your own endpoint (?my-endpoint=posts) and use get_posts( array('fields' => 'ids') );?
    – deflime
    Jun 21 at 18:36
  • 3
    doing this does not cut down on database queries, there will be just as many queries since WordPress will fetch the entire post regardless, and it takes just as many queries to fetch 5 rows of the post table as it does to fetch just the ID column of 5 rows of the post table. This will not improve database performance., at best you will get some minor savings on bandwidth which are then immediately eliminated when you make individual requests for each post. Also, if you have an object cache then the full post object is stored there already so it doesn't hit the database fetching it
    – Tom J Nowell
    Jun 21 at 19:05
  • @TomJNowell ah, gotcha, I had just assumed that it would be more performant returning less fields but I guess that's now how it works under the hood. Thanks for the info! Jun 21 at 19:30
  • GraphQL is best at giving you precisely what you want and only what you want, but it doesn't scale, if it's scale and speed you want, then what you need is super cachable cookie cutter responses. Respond with the full post and do it from cache so the DB doesn't get hit at all, if you can remove the need to load WordPress entirely via something like Varnish or Nginx caches even better
    – Tom J Nowell
    Jun 21 at 22:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.