按类别过滤Wordpress帖子时对GatsbyJS页面进行分页 [英] Paginating GatsbyJS pages when filtering Wordpress posts by category

查看:53
本文介绍了按类别过滤Wordpress帖子时对GatsbyJS页面进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在按类别过滤Wordpress帖子时,谁能对我如何在Gatsby中分页有一些见识?

Can anyone shed some insight on how I would go about paginating pages in Gatsby when filtering Wordpress posts by category?

对于上下文,我的gatsby节点文件:

For context, my gatsby-node file:


const path = require('path')


module.exports.createPages = async ({ graphql, actions }) => {

 // import { paginate } from 'gatsby-awesome-pagination';


  const { createPage } = actions
  const blogPostTemplate = path.resolve('./src/templates/blog-post.js')
  const blogCategoryFilter = path.resolve('./src/templates/blog-filter-category.js')
  const blogArchiveFilter = path.resolve('./src/templates/blog-filter-archive.js')

  const res = await graphql(`
      query {
        allWordpressPost {
          edges {
            node {
              slug
              date(formatString:"YYYY-MM")
            }
          }
        }
        allWordpressCategory {
          edges {
            node {
              slug
            }
          }
        }
      }
    `)

 // UNPAGINATED
  //Blog list - organized by category
  res.data.allWordpressCategory.edges.forEach((edge) => {
    createPage({
      component: blogCategoryFilter,
      path: `/blog/category/${edge.node.slug}`,
      context: {
        slug: edge.node.slug,
      }
    })
  })
}

我用作模板的blog-filter-category.js文件:

The blog-filter-category.js file that I use as my template:

import React from 'react'
import { graphql, Link } from 'gatsby'

import Layout from '../components/layout'
import BlogNav from '../components/blognav'

import blogStyles from '../components/modules/blog.module.css'

export const query = graphql`
  query($slug: String!) {
    allWordpressPost (filter: {categories: {elemMatch: {slug: { eq: $slug }}}}) {
      edges {
        node {
          title
          slug
          content
          date(formatString: "MMMM DD, YYYY")
        }
      }
    }
  }
`






export default ({ data }) => {
  //const post = data.allWordpressPost.edges[0].node
  return (
    <Layout>
      <div className={blogStyles.blog_container}>
        <div className={blogStyles.blogContent_container}>
          <ol>
            {data.allWordpressPost.edges.map((edge) => {
              return (
                <div className={blogStyles.blogPost_container}>
                  <li className={blogStyles.blog_list}>
                    <h2><Link to={`/blog/${edge.node.slug}`} className={blogStyles.blog_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
                    <p className={blogStyles.blog_date}>{edge.node.date}</p>
                    <p className={blogStyles.blog_content} dangerouslySetInnerHTML={{ __html: edge.node.content }} />
                  </li>
                </div>
              )
            })}
          </ol>
        </div>
        <BlogNav />
      </div>

    </Layout>
  )
}

我尝试阅读一些相关插件(gatsby-paginate,gatsby-awesome-paginate等)的文档和本文( https://www.gatsbycentral.com/pagination-in-gatsby ),但这一切都让我有些头疼.对于我正在生成模板并按时间顺序排序的博客帖子,这似乎很有意义,但是当我开始按类别,归档月份等进行过滤时,我会感到困惑.

I tried reading through the documentation of some relevant plugins (gatsby-paginate, gatsby-awesome-paginate, etc) and this article (https://www.gatsbycentral.com/pagination-in-gatsby) but it was all going a little over my head. It seemed to make sense for blog posts that I'm generating on to a template and simply sorting chronologically, but I get confused when I start filtering by category, archived months, etc.

有什么秘诀吗?我可以使用上面的代码结构进行分页,还是必须重新考虑如何将它们组合在一起?

Any tips? Can I paginate using the code structures above or do I have to rethink how I'm throwing this together?

谢谢!

推荐答案

假设我们选择使用问题中提到的 gatsby-awesome-pagination 插件.

Let's assume we chose to use the gatsby-awesome-pagination plugin, as mentioned in the question.

这来自于插件的快速启动说明:

This is from the plugin's quick start instructions:

import { paginate } from 'gatsby-awesome-pagination';

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions;

  // Fetch your items (blog posts, categories, etc).
  const blogPosts = doSomeMagic();

  // Create your paginated pages
  paginate({
    createPage, // The Gatsby `createPage` function
    items: blogPosts, // An array of objects
    itemsPerPage: 10, // How many items you want per page
    pathPrefix: '/blog', // Creates pages like `/blog`, `/blog/2`, etc
    component: path.resolve('...'), // Just like `createPage()`
  })
}

我们感兴趣的是按类别进行分页:

What we're interested in in order to paginate by category is:

  1. :我们需要一个按类别分组的帖子数组
  2. pathPrefix :要生成路径的类别名称
  1. items: we need an array of posts grouped by category
  2. pathPrefix: the category name to generate paths

我们可以通过GraphQL查询获得这些信息:

We can get these by using a GraphQL query:

query MyQuery {
  allWordpressPost {
    group(field: categories___name) {
      nodes {
        title
        # any other post data you need
      }
      fieldValue
    }
  }
}

这将返回类似的内容:

{
  "data": {
    "allWordpressPost": {
      "group": [
        {
          "nodes": [
            {
              "title": "Abyssinians"
            }
          ],
          "fieldValue": "Cats"
        },
        {
          "nodes": [
            {
              "title": "Teckels"
            },
            {
              "title": "Poodles"
            }
          ],
          "fieldValue": "Dogs"
        }
      ]
    }
  }
}

现在,我们可以在 gatsby-node.js 中创建分页页面.一个实现可能看起来像这样:

Now we can create paginated pages in gatsby-node.js. An implementation could look like this:

import { paginate } from 'gatsby-awesome-pagination';

exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions;

  const { data } = await graphql(`
    query {
      allWordpressPost {
        group(field: categories___name) {
          nodes {
            title
            # any other post data you need
          }
          fieldValue
        }
      }
    }
  `)

  // create paginated pages for each category
  data.allWordpressPost.group.forEach(({ nodes: posts, fieldValue: category }) => {
    paginate({
      createPage,
      items: posts,
      itemsPerPage: 10,
      pathPrefix: category, // use category name for pages
      component: path.resolve('...'), // your template for post lists
    })

    // TODO create a page for each post
    // you can do it manually or use the plugin's `createPagePerItem` API:
    // https://github.com/GatsbyCentral/gatsby-awesome-pagination#createpageperitem
  }
}

关键是要利用GraphQL来构建正确的查询.

The key here is to take advantage of GraphQL to build the right query.

希望有帮助!

这篇关于按类别过滤Wordpress帖子时对GatsbyJS页面进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆