【问题标题】:Gatsby fetching Wordpress Custom Post Types and create pagesGatsby 获取 Wordpress 自定义帖子类型并创建页面
【发布时间】:2021-12-13 19:14:32
【问题描述】:

我阅读了文档并尝试了几个教程,但我一直坚持使用 GatsbyJS 获取自定义帖子类型。

我尝试了几种方法,但都没有按预期工作。我总是收到 404。

这是我正在使用的 sn-p 的一部分,它适用于页面和帖子,但不适用于自定义帖子类型。 项目页面应在项目子文件夹/路径下创建。喜欢:example.com/project/my-first-project

gatsby-node.js 的部分看起来像这样:

const createSinglePages = async ({ posts, gatsbyUtilities }) =>
  Promise.all(
    posts.map(({ previous, post, next }) =>
      // createPage is an action passed to createPages
      // See https://www.gatsbyjs.com/docs/actions#createPage for more info
      gatsbyUtilities.actions.createPage({
        // Use the WordPress uri as the Gatsby page path
        // This is a good idea so that internal links and menus work ????
        path: post.uri,

        // use the blog post template as the page component
        component: path.resolve(
          `./src/templates/${post.__typename.replace(`Wp`, ``)}.js`
        ),

        // `context` is available in the template as a prop and
        // as a variable in GraphQL.
        context: {
          // we need to add the post id here
          // so our blog post template knows which blog post
          // the current page is (when you open it in a browser)
          id: post.id,

          // We also use the next and previous id's to query them and add links!
          previousPostId: previous ? previous.id : null,
          nextPostId: next ? next.id : null,
        },
      })
    )
  );

src/template/project.js 文件如下所示:

import React from "react";
import { Link, graphql } from "gatsby";
import Image from "gatsby-image";
import parse from "html-react-parser";

import Layout from "../components/Layout";
import Seo from "../components/Seo";

const ProjectTemplate = ({ data: { post } }) => {
  const featuredImage = {
    fluid: post.featuredImage?.node?.localFile?.childImageSharp?.fluid,
    alt: post.featuredImage?.node?.alt || ``,
  };

  return (
    <Layout>
      <Seo title={post.title} description={post.excerpt} />

      <article
        className="blog-post"
        itemScope
        itemType="http://schema.org/Article"
      >
        <header>
          <h1 itemProp="headline">{parse(post.title)}</h1>
          <p>{post.date}</p>

          {/* if we have a featured image for this post let's display it */}
          {featuredImage?.fluid && (
            <Image
              fluid={featuredImage.fluid}
              alt={featuredImage.alt}
              style={{ marginBottom: 50 }}
            />
          )}
        </header>

        {!!post.content && (
          <section itemProp="articleBody">{parse(post.content)}</section>
        )}
      </article>
    </Layout>
  );
};

export default ProjectTemplate;

export const pageQuery = graphql`
  query ProjectById(
    # these variables are passed in via createPage.pageContext in gatsby-node.js
    $id: String!
  ) {
    # selecting the current post by id
    post: wpProject(id: { eq: $id }) {
      id
      content
      title
      date(formatString: "MMMM DD, YYYY")
      featuredImage {
        node {
          altText
          localFile {
            childImageSharp {
              fluid(maxWidth: 1000, quality: 100) {
                ...GatsbyImageSharpFluid_tracedSVG
              }
            }
          }
        }
      }
    }
  }
`;

Gatsby API 是否会自动创建子文件夹,还是我需要为每种帖子类型在某处定义该子文件夹?

任何帮助表示赞赏!

【问题讨论】:

  • “子文件夹”是什么意思?
  • 我的意思是子路径。我有一个名为 project 的自定义帖子类型,所以我想列出子路径下的所有项目,例如:expample.com/projects/ 并在此子路径中动态创建页面。跨度>

标签: reactjs wordpress gatsby


【解决方案1】:

您在路径field 下定义“子文件夹”:

  gatsbyUtilities.actions.createPage({
        path: post.uri,
            component: path.resolve(
          `./src/templates/${post.__typename.replace(`Wp`, ``)}.js`
        ),

        context: {
          id: post.id,
          previousPostId: previous ? previous.id : null,
          nextPostId: next ? next.id : null,
        },
      })

您只需要执行以下操作:

path: `projects/${post.id}`

在此处检查斜杠和尾部斜杠。

如果您获取动态项目类型的信息以获得更自动化的方法(假设它是 post.__typename),您可以将 projects 替换为您的动态项目类型。

【讨论】:

    【解决方案2】:

    为了在 WPGraphQL 中使用自定义帖子类型,您必须使用以下字段将帖子类型配置为 show_in_graphql:

    show_in_graphql:真

    注册新的自定义帖子类型时 这是注册新的“文档”post_type 并启用 GraphQL 支持的示例。

    add_action( 'init', function() {
       register_post_type( 'docs', [
          'show_ui' => true,
          'labels'  => [
            //@see https://developer.wordpress.org/themes/functionality/internationalization/
            'menu_name' => __( 'Docs', 'your-textdomain' ),
          ],
          'show_in_graphql' => true,
          'hierarchical' => true,
          'graphql_single_name' => 'document',
          'graphql_plural_name' => 'documents',
       ] );
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      相关资源
      最近更新 更多