準備與Gatsby探索無頭WordPress了嗎?本文深入研究了搜索功能,將WordPress的本機搜索與JetPack Instant Search進行了比較。我們將構建一個利用gatsby-source-wordpress
插件(在2021年3月3日在Gatsby 3中引入)和WPGRAPHQL的蓋茨比網站,以進行更平滑的WordPress集成。
通過構建蓋茨比WP主題的經驗來了解這一探索,這是一個為開發人員創建由WordPress提供動力的開發人員的市場。我們將重點介紹兩種搜索方法:利用WordPress的內置搜索和實現JetPack Instant Search。
讓我們使用gatsby-starter-wordpress-blog
啟動器創建一個蓋茨比網站:
蓋茨比新的gatsby-wordpress-w-search https://github.com/gatsbyjs/gatsby-starter-wordpress-blog
此入門提供了基本的帖子和博客頁面路由。在我們的示例中,我們將從搜索結果中排除頁面。我們將使用啟動器的WordPress演示;如果使用自己的,請記住必要的WordPress插件:WPGRAPHQL(對於GraphQL API)和WPGATSBY(用於蓋茨比特定的架構修改並構建優化)。兩者都可以通過WordPress插件存儲庫獲得。
Gatsby通常使用頁面查詢或useStaticQuery
進行數據獲取。但是,對於用戶啟動的搜索,我們需要動態解決方案。我們將使用Apollo客戶端直接與WPGRAPHQL API進行交互,處理數據請求和緩存。
安裝阿波羅客戶端:
紗線添加 @apollo/client crossfetch
使用Gatsby的wrapRootElement
API將應用程序與gatsby-browser.js
中的ApolloProvider
包裝:
// gatsby-browser.js // ...(進口)... const client =新的apolloclient({{ // ...(鏈接和緩存配置)... URI:“ https://wpgatsbydemo.wpengine.com/graphql”,//用graphql endpoint替換 提取:雜交, }); 導出const wraprootlement =({element})=>( <apolloprovider client="{client}">{元素}</apolloprovider> );
創建必要的文件:
觸摸src/components/search.js src/components/search-form.js src/components/search-results.js src/css/search.css
Search
組件管理搜索術語狀態並呈現形式和結果:
// src/components/search.js // ...(進口)... const search =()=> { const [searchTerm,setSearchTerm] = usestate(“”); 返回 ( <div classname="search-container"> <searchform setsearchterm="{setSearchTerm}"></searchform> {搜索術語&&<searchresults searchterm="{searchTerm}"></searchresults> } </div> ); };
SearchForm
是一個簡單的形式:
// src/components/search-form.js // ...(進口)... const searchForm =({setSearchTerm})=> { // ...(狀態和handlesubmit函數)... 返回 (
SearchResults
使用Apollo客戶端的useQuery
鉤:
// src/components/search-results.js // ...(進口)... const get_results = gql` 查詢($ searchTerm:string){ 帖子(其中:{搜索:$ searchTerm}){ 邊緣{ 節點{ ID Uri 標題 摘抄 } } } } `; const searchResults =({{搜索term})=> { const {data,loading,error} = usequery(get_results,{variables:{searchTerm}}); // ...(加載,錯誤和數據處理)... };
將Search
組件添加到佈局中(或使用wrapPageElement
進行持久顯示)。本文的其餘部分詳細介紹了分頁,持續搜索,處理帖子和頁面,並使用JetPack即時搜索增強的搜索功能。提供的代碼片段為蓋茨比網站內建立強大的搜索功能提供了基礎。
以上是本機搜索與JetPack Instant interment search在無頭Wordpress中使用Gatsby的詳細內容。更多資訊請關注PHP中文網其他相關文章!