Add search functionality (powered by Lunr.js) to your Gatsby site based on Wordpress data.
The plugin filters post title, post content and all ACF fields.
Gatsby plugin: gatsby-source-wordpress
-
Upload the PHP file inside the plugin folder (see GitHub) as a plugin into Wordpress. Once this is done you should be able to see the json output at "/wp-json/wp/v2/searchResults".
-
Include the route in your gatsby-config.js
{
resolve: "gatsby-source-wordpress",
options: {
...
includedRoutes: ["**/searchResults"]
}
}
- Install the search component
yarn add gatsby-wordpress-search
or
npm i gatsby-wordpress-search
- Import the component and style it.
import React from "react";
import { StaticQuery, graphql, navigate } from "gatsby";
import styled from "styled-components";
import Search from "gatsby-wordpress-search";
<Wrapper>
<StaticQuery
query={graphql`
{
allWordpressWpSearchResults {
edges {
node {
id
post_title
searchData
pathname
}
}
}
}
`}
render={data => {
return (
<Search
data={data}
minCharacters={4}
contentCharacters={300}
maxResults={10}
placeholder='Search'
onSelect={object => navigate(o.pathname)}
/>
);
}}
/>
</Wrapper>;
const Wrapper = styled.div`
.container {
}
.input {
}
.suggests {
}
.suggest {
}
.suggestTitle {
}
.suggestContent {
}
`;