【问题标题】:Paginating GatsbyJS pages when filtering Wordpress posts by category按类别过滤 Wordpress 帖子时对 GatsbyJS 页面进行分页
【发布时间】:2020-04-12 14:26:28
【问题描述】:

在按类别过滤 Wordpress 帖子时,任何人都可以了解如何在 Gatsby 中对页面进行分页吗?

对于上下文,我的 gatsby-node 文件:


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 文件:

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),但这一切都让我有点不知所措。对于我在模板上生成并按时间顺序简单排序的博客文章似乎很有意义,但是当我开始按类别、存档月份等进行过滤时,我会感到困惑。

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

谢谢!

【问题讨论】:

标签: javascript wordpress pagination graphql gatsby


【解决方案1】:

假设我们选择使用gatsby-awesome-pagination 插件,如问题中所述。

这是来自插件的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()`
  })
}

为了按类别分页,我们感兴趣的是:

  1. items:我们需要一个按类别分组的帖子数组
  2. pathPrefix:生成路径的类别名称

我们可以通过使用 GraphQL 查询来获得这些:

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 中创建分页页面。实现可能如下所示:

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 来构建正确的查询。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2012-10-04
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2020-12-20
    相关资源
    最近更新 更多