Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get a list of all posts under a specific WordPress category? #196

Open
3zmx opened this issue Oct 27, 2024 · 1 comment
Open

How to get a list of all posts under a specific WordPress category? #196

3zmx opened this issue Oct 27, 2024 · 1 comment

Comments

@3zmx
Copy link

3zmx commented Oct 27, 2024

As per the title, I want to fetch all posts under a specific category, but I couldn't find the relevant method in the composables from the documentation. Could someone help me with this? Is there something like useWPPostsByCategory()?

thanks : )

@vernaillen
Copy link
Collaborator

vernaillen commented Oct 27, 2024

Thanks for trying out the WPNuxt module!

You are right that the module doesn't provide this query by default, but it is very easy to add it.

All you have to do is add a graphql query in the extend/queries as explained here: https://wpnuxt.com/docs/composables/custom-queries

So in your case you could add this file: [srcDir]/extend/queries/PostsByCategory.gql
with this content:

#import "~/.queries/fragments/Post.fragment.gql"

query PostsByCategoryId($categoryId: Int!) {
  posts(where: {categoryId: $categoryId}) {
    nodes {
      ...Post
    }
  }
}

query PostsByCategoryName($categoryName: String!) {
  posts(where: {categoryName: $categoryName}) {
    nodes {
      ...Post
    }
  }
}

When you start nuxt 2 new composables will automatically be generated, and can be used like this:

useWPPostsByCategoryId:

const { data } = await useWPPostsByCategoryId({ categoryId: 1 })

useWPPostsByCategoryName:

const { data } = await useWPPostsByCategoryName({ categoryName: 'myCategory' })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants