Filtering Data by Slug in GraphQL

Thumbnail

Written by: developervsandhu

Technology and Gadgets

Filtering Data by Slug in GraphQL

If you’re working with a WordPress installation and need to fetch specific data using GraphQL, you can filter your queries by a slug. Here’s how you can do it:

Example Query:

query GetDestinationBySlug($slug: String!) {
  destinationBy(slug: $slug) {
    title
    Destinations {
      fullDescription {
        title
        FullDescription
      }
    }
  }
}

Explanation:

  • $slug: String!: This defines a variable named slug that must be provided (indicated by the exclamation mark !).
  • destinationBy(slug: $slug): This is the part where we filter the results based on the provided slug. It returns the specific destination that matches the slug.
  • Inside the destinationBy block, you can retrieve the desired fields, such as:
    • title: The title of the destination.
    • Destinations { fullDescription { title FullDescription } }: This retrieves the full description for the destination, including its title and full details.

Fetching Data Using JavaScript:

You can use the following JavaScript code to send the query to your WordPress GraphQL endpoint:

const fetchDestinationBySlug = async (slug) => {
  const query = `
    query GetDestinationBySlug($slug: String!) {
      destinationBy(slug: $slug) {
        title
        Destinations {
          fullDescription {
            title
            FullDescription
          }
        }
      }
    }
  `;

  const variables = { slug: slug };

  const response = await fetch('https://your-wordpress-site.com/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: query,
      variables: variables,
    }),
  });

  const result = await response.json();
  console.log(result.data.destinationBy);
};

// Example usage
fetchDestinationBySlug('example-slug');

Summary

This query is a great way to get precise data from your WordPress site using GraphQL! Feel free to reach out if you have any questions or need further assistance! 💬

Login To Add Comment

No comments yet.