pacf和acf_如何通過Wordpress API,ACF和Express.js使Wordpress更加令人興奮

pacf和acf

by Tyler Jackson

泰勒·杰克遜(Tyler Jackson)

如何通過Wordpress API,ACF和Express.js使Wordpress更加令人興奮 (How to make Wordpress more exciting with the Wordpress API, ACF, & Express.js)

I’ve been working with Wordpress since it’s proliferation as a content management system. I hardly get excited when clients or co-workers mention it anymore. I’ve “found the light” in more robust frameworks and learned much more about the different parts of custom web applications.

我一直在與Wordpress合作,因為它已經發展成為內容管理系統。 當客戶或同事再提及它時,我幾乎不會感到興奮。 我已經在更強大的框架中“找到了亮點”,并且了解了更多有關自定義Web應用程序不同部分的知識。

So, in an effort to rejuvenate my passion for Wordpress, I’ve started looking at different ways to implement the framework. One of those ways is to separate the front-end from the back-end and avoid some of the pain points of using the Wordpress Template Tags and theming system. Let’s take a look.

因此,為了振興對Wordpress的熱情,我開始尋找實現框架的不同方法。 其中一種方法是將前端與后端分開,并避免使用Wordpress模板標簽和主題系統的某些痛點。 讓我們來看看。

整體與分布式應用 (Monolithic vs. Distributed Apps)

Wordpress is a monolithic framework, meaning the different parts of the framework (database, file storage, presentation structure & asset files, business logic files) are all packaged together. This is a large part of why Wordpress is so easy to get up and running. Install MAMP, copy over the latest Wordpress files, create a database, and change the wp-config.php file. Good to go.

WordPress是一個整體框架,意味著框架的不同部分(數據庫,文件存儲,表示結構和資產文件,業務邏輯文件)都打包在一起。 這就是為什么Wordpress如此容易啟動和運行的很大一部分。 安裝MAMP,復制最新的Wordpress文件,創建數據庫,然后更改wp-config.php文件。 好去。

We are going to go against the monolithic convention and break this Wordpress site up into two different parts: front-end and back-end, presentation and administration.

我們將違反整體慣例,并將此Wordpress網站分為兩個不同部分:前端和后端,演示和管理。

We are going to use Wordpress for the data administration of our app and leverage a plugin to help with the creation and management of attributes (fields) for our custom post type. For the presentation side of things, we are going to forego a theme entirely and consume API endpoints from an Express.js application.

我們將使用Wordpress進行應用程序的數據管理,并利用插件來幫助創建和管理自定義帖子類型的屬性(字段)。 對于表示方面,我們將完全放棄主題,并使用Express.js應用程序中的API端點。

(Example)

In this example, we are going to build a simple product listing. The idea is that you already have a website powered by Wordpress, and would like to manage a list of products for sale through the same interface. But you want to create a completely different website for the store.

在此示例中,我們將構建一個簡單的產品清單。 這個想法是,您已經有一個由Wordpress支持的網站,并且希望通過相同的界面來管理要出售的產品列表。 但是您想為商店創建一個完全不同的網站。

WordPress API (Wordpress API)

Since version 4.7, Wordpress is automatically exposing your published posts (and other data) via its REST API, presented in a JSON format. If you’ve developed a website using Wordpress 4.7+, simply add /wp-json to the root URL and marvel at the wall of text that’s returned.

從4.7版開始,Wordpress將通過其REST API自動以JSON格式顯示您發布的帖子(和其他數據)。 如果您使用Wordpress 4.7+開發了一個網站,只需將/wp-json添加到根URL并驚嘆于返回的文本墻。

With this API automatically integrated into the Wordpress installation, a lot of the work of a distributed application is already done for us. API creation can be a roadblock when getting started with this new way of thinking about applications. Wordpress has created a fantastic, basic API for consuming our data any way we prefer.

通過將此API自動集成到Wordpress安裝中,我們已經為分布式應用程序完成了許多工作。 開始使用這種新的應用程序思考方式時,API的創建可能會成為一個障礙。 WordPress已創建了一個出色的基本API,可以按我們喜歡的任何方式使用我們的數據。

At this point, I would only be cluttering the internet by writing a tutorial on how to locally install Wordpress. So instead, I’m going to point you towards a trusted source on the subject.

在這一點上,我只會寫一篇關于如何本地安裝Wordpress的教??程來使互聯網混亂。 因此,我將帶您前往該主題的可信賴來源 。

No matter what path you take to get a Wordpress instance up and running, you should be able to access it via http://localhost or some other URL. Once we have a URL, let’s do a quick test to make sure we have data coming back. I prefer a tool like Postman, but we’ll keep it simple and visit the following URL in our browser (changing the URL accordingly, of course).

無論您采用什么方式啟動和運行Wordpress實例,都應該能夠通過http://localhost或其他URL對其進行訪問。 有了URL后,讓我們進行快速測試以確保我們有返回的數據。 我更喜歡Postman之類的工具,但我們將使其保持簡單并在瀏覽器中訪問以下URL(當然,相應地更改URL)。

http://localhost/mysite/wp-json

http://localhost/mysite/wp-json

This should return a list of all the available endpoints for your Wordpress installation’s REST API.

這應該返回您的Wordpress安裝的REST API的所有可用端點的列表。

But for real, Postman…

但實際上,郵遞員…

PostmanPostman is the only complete API development environment, for API developers, used by more than 5 million developers…www.getpostman.com

Postman Postman是API開發人員的唯一完整的API開發環境,已有超過500萬開發人員使用。

自定義帖子類型 (Custom Post Types)

Since Wordpress limits us to two data types (Posts & Pages) we are going to need to create a custom post type for our Products. This will create a clear separation from the Product posts and any other posts we have.

由于Wordpress將我們限制為兩種數據類型(“帖子和頁面”),因此我們需要為“產品”創建自定義帖子類型。 這將與產品帖子以及我們擁有的任何其他帖子明確區分開。

There are a number of different ways to create custom post types. Here, we are going to create a single file Wordpress Plugin to register the Products post type.

創建自定義帖子類型的方法有多種。 在這里,我們將創建一個文件Wordpress Plugin來注冊Products帖子類型。

<?php/*Plugin Name: Product Custom Post Type*/
function create_product_cpt() {  $labels = array(   'name' => __( 'Products', 'Post Type General Name', 'products' ),   'singular_name' => __( 'Product', 'Post Type Singular Name', 'products' ),   'menu_name' => __( 'Products', 'products' ),   'name_admin_bar' => __( 'Product', 'products' ),   'archives' => __( 'Product Archives', 'products' ),   'attributes' => __( 'Product Attributes', 'products' ),   'parent_item_colon' => __( 'Parent Product:', 'products' ),   'all_items' => __( 'All Products', 'products' ),   'add_new_item' => __( 'Add New Product', 'products' ),   'add_new' => __( 'Add New', 'products' ),   'new_item' => __( 'New Product', 'products' ),   'edit_item' => __( 'Edit Product', 'products' ),   'update_item' => __( 'Update Product', 'products' ),   'view_item' => __( 'View Product', 'products' ),   'view_items' => __( 'View Products', 'products' ),   'search_items' => __( 'Search Product', 'products' ),   'not_found' => __( 'Not found', 'products' ),   'not_found_in_trash' => __( 'Not found in Trash', 'products' ),   'featured_image' => __( 'Featured Image', 'products' ),   'set_featured_image' => __( 'Set featured image', 'products' ),   'remove_featured_image' => __( 'Remove featured image', 'products' ),   'use_featured_image' => __( 'Use as featured image', 'products' ),   'insert_into_item' => __( 'Insert into Product', 'products' ),   'uploaded_to_this_item' => __( 'Uploaded to this Product', 'products' ),   'items_list' => __( 'Products list', 'products' ),   'items_list_navigation' => __( 'Products list navigation', 'products' ),   'filter_items_list' => __( 'Filter Products list', 'products' ),  );
$args = array(   'label' => __( 'Product', 'products' ),   'description' => __( '', 'products' ),   'labels' => $labels,   'menu_icon' => 'dashicons-products',   'supports' => array('title', 'editor', 'excerpt', 'thumbnail'),   'taxonomies' => array('products'),   'public' => true,   'show_ui' => true,   'show_in_menu' => true,   'menu_position' => 5,   'show_in_admin_bar' => true,   'show_in_nav_menus' => true,   'can_export' => true,   'has_archive' => true,   'hierarchical' => false,   'exclude_from_search' => false,   'show_in_rest' => true,   'rest_base' => 'products',   'publicly_queryable' => true,   'capability_type' => 'post',  );
register_post_type( "product", $args );}%>

While long-winded, this is pretty standard code for creating a custom post type in Wordpress. Two things to note in our $args array:

盡管過程繁瑣,但這是在Wordpress中創建自定義帖子類型的非常標準的代碼。 $args數組中需要注意兩件事:

  • 'show_in_rest' => true makes the custom post type accessible via the REST API

    'show_in_rest' => t rue可以通過REST API訪問自定義帖子類型

  • 'rest_base' => 'products' sets the name we use to access Products via the REST API endpoints

    'rest_base' => 'produc ts'設置我們用于通過REST API端點訪問產品的名稱

Once you have your custom post type showing in the Wordpress admin, let’s make sure we can get a response via the API (you’ll need to create a product so it doesn’t return empty).

一旦您的自定義帖子類型顯示在Wordpress管理員中,請確保我們可以通過API得到響應(您需要創建一個產品,因此它不會返回空)。

http://localhost/mysite/wp-json/wp/v2/products

http://localhost/mysite/wp-json/wp/v2/products

And here’s what we get…

這就是我們得到的...

Sweet!

甜!

高級自定義字段 (Advanced Custom Fields)

I try to limit my usage of plugins as much as possible, but I’ll make an exception for Advanced Custom Fields (ACF). ACF takes all the work out of creating and managing custom fields for post types. Head to your Plugins page, search for Advanced Custom Fields then click “Install” & “Activate”. All done.

我嘗試盡可能限制插件的使用,但是我將對“高級自定義字段(ACF)”作為例外。 ACF將所有工作排除在為帖子類型創建和管理自定義字段之外。 轉到“插件”頁面,搜索“高級自定義字段”,然后單擊“安裝”和“激活”。 全做完了。

It would also be redundant for me to walk you through creating a Field Group using Advanced Custom Fields, so I’ll let their documentation walk you through it if you don’t know how.

對于我來說,引導您使用“高級自定義字段”創建字段組也將是多余的,因此,如果您不知道如何操作, 我將讓其文檔指導您完成該過程。

Let’s create a Field Group called “Product Meta” and add fields for “Normal Price”, “Discount Price” and “Inventory Quantity” and position them in the sidebar area.

讓我們創建一個名為“產品元”的字段組,并為“正常價格”,“折扣價”和“庫存數量”添加字段并將它們放置在側邊欄區域中。

Good.

好。

Now comes the tricky part. The fields we just created through ACF aren’t exposed via the REST API by default. We will have to leverage add_filter and rest_prepare_{$post_type} to add the custom field values to the JSON response. Here, I’ve simply added this bit of code to the bottom of our custom post type plugin file for the sake of brevity.

現在是棘手的部分。 默認情況下,我們通過ACF創建的字段不會通過REST API公開。 我們將不得不利用add_filterrest_prepare_{$post_type}將自定義字段值添加到JSON響應中。 在這里,為了簡潔起見,我只是將這段代碼添加到了自定義帖子類型插件文件的底部。

function my_rest_prepare_post($data, $post, $request) {  $_data = $data->data;    $fields = get_fields($post->ID);
foreach ($fields as $key => $value){    $_data[$key] = get_field($key, $post->ID);  }
$data->data = $_data;    return $data;}
add_filter("rest_prepare_product", 'my_rest_prepare_post', 10, 3);

Thanks to Cody Sand for the tidbit above.

感謝Cody Sand的上述建議。

Express.js (Express.js)

Our Express.js app will provide us a framework for consuming the Wordpress API and presenting products in our store website. Since we are simply consuming an API, we could use any framework of our choosing. Vue.js. Angular. Backbone. React. Rails. Django. Middleman. Jekyll. The front-end world is your oyster.

我們的Express.js應用將為我們提供一個使用Wordpress API并在我們的商店網站中展示產品的框架。 由于我們只是在使用API??,因此可以使用我們選擇的任何框架。 Vue.js。 有角度的。 骨干。 React 滑軌。 Django的。 中間人。 杰基爾 前端世界就是您的牡蠣。

I’ll assume you already have Node.js installed. If you don’t, it’s dead simple. Let’s start a new Express.js app.

我假設您已經安裝了Node.js。 如果不這樣做, 那就太簡單了 。 讓我們啟動一個新的Express.js應用程序。

npm install -g express-generator nodemonexpress --css=sass --view=jade --git mystorecd mystorenpm install --save request request-promise && npm install

Here, we are using the Express Generator package to generate a skeleton for our Express app. We’ll also be using SASS for stylesheets and Jade Template Engine. Choose whatever you’re comfortable with. Nodemon will restart our app automatically for us when a file changes, and the Request library will help us make HTTP requests to the Wordpress API. Let’s serve up our Express app:

在這里,我們使用Express Generator軟件包為Express應用程序生成框架。 我們還將對樣式表和Jade模板引擎使用SASS。 選擇您喜歡的任何東西。 文件更改時,Nodemon將自動為我們重新啟動我們的應用程序,并且請求庫將幫助我們向Wordpress API發出HTTP請求。 讓我們提供Express應用程序:

nodemon

nodemon

Now, when we pull up http://localhost:3000 we should see our Express app running.

現在,當我們拉起http://localhost:3000我們應該看到Express應用程序正在運行。

Alright, now let’s pull in our products.

好吧,現在讓我們引入我們的產品。

var express = require('express');var router = express.Router();const rp = require('request-promise');
/* GET index page. */router.get('/', function(req, res, next) {  rp({uri: 'http://127.0.0.1:8888/test/wp-json/wp/v2/products', json: true})  .then((response) => {    console.log(response);    res.render('index', {products: response});  })  .catch((err) => {    console.log(err);  });});
module.exports = router;

In our index.js route file, let’s include the Request-Promise library then make a call to the products endpoint within our root route (/).

在我們的index.js路由文件中,讓我們包括Request-Promise庫,然后在根路由( / )中調用products端點。

If the request is successful, then we render our index view. If there’s an error with the request, we simply log it. Now, the view…

如果請求成功,則我們呈現index視圖。 如果請求有錯誤,我們只需將其記錄下來。 現在,風景…

extends layout
block content h1 MyStore ul  each product in products   li    product.title.rendered    product.price

Using Jade, we will simply list the products out. Ok, let’s check out our store site.

使用Jade,我們將簡單列出產品。 好的,讓我們看看我們的商店網站。

? There’s your prize. I’ll leave it up to you to continue down the Express road and figure out how to get product listing and index pages working.

? 有你的獎品。 我將由您決定繼續沿Express道路前進,并弄清楚如何使產品列表和索引頁面正常工作。

超越 (Beyond)

This is a fairly simple example of how distributed apps work using Wordpress. We could have continued to separate the app into even more parts by integrating a CDN for media storage or moving the database to a separate server. We also didn’t cover authentication for the Wordpress API which is something you would absolutely need in production.

這是一個使用Wordpress的分布式應用程序工作方式的非常簡單的示例。 通過集成用于媒體存儲的CDN或將數據庫移至單獨的服務器,我們可以繼續將應用程序分成更多部分。 我們也沒有介紹Wordpress API的身份驗證,這是您在生產中絕對需要的。

From here, you could implement Stripe or another payment processor and have a fully functional store site. I hope this has inspired some of you to leverage Wordpress in different ways and continue using one of the most ubiquitous CMS solutions out there. Happy coding!

從這里,您可以實現Stripe或其他付款處理器,并擁有功能齊全的商店站點。 我希望這啟發了你們中的一些人以不同的方式利用Wordpress,并繼續使用其中一種最普遍的CMS解決方案。 編碼愉快!

翻譯自: https://www.freecodecamp.org/news/how-to-make-wordpress-more-exciting-with-the-wordpress-api-acf-express-js-9dc33b8fb133/

pacf和acf

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394250.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394250.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394250.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python運行出現數據錯誤_Python運行出錯情況

1、錯誤內容&#xff1a;You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory str). It is highly recommended that you instead just switch your application to Unicode strings.錯誤描述&#x…

leetcode95. 不同的二叉搜索樹 II(遞歸)

給定一個整數 n&#xff0c;生成所有由 1 ... n 為節點所組成的 二叉搜索樹 。示例&#xff1a;輸入&#xff1a;3 輸出&#xff1a; [[1,null,3,2],[3,2,null,1],[3,1,null,null,2],[2,1,3],[1,null,2,null,3] ] 解釋&#xff1a; 以上的輸出對應以下 5 種不同結構的二叉搜索樹…

數據結構探險系列—棧篇-學習筆記

數據結構探險—棧篇 什么是棧&#xff1f; 古代棧就是牲口棚的意思。 棧是一種機制&#xff1a;后進先出 LIFO&#xff08;last in first out&#xff09; 電梯 棧要素空棧。棧底&#xff0c;棧頂。沒有元素的時候&#xff0c;棧頂和棧底指向同一個元素&#xff0c;如果加入新元…

MYSQL遠程登錄權限設置 ,可以讓Navicat遠程連接服務器的數據庫

Mysql默認關閉遠程登錄權限&#xff0c;如下操作允許用戶在任意地點登錄&#xff1a;1. 進入mysql&#xff0c;GRANT ALL PRIVILEGES ON *.* TO root% IDENTIFIED BY WITH GRANT OPTION;IDENTIFIED BY后跟的是密碼&#xff0c;可設為空。2. FLUSH privileges; 更新Mysql為了安…

time series 時間序列 | fractional factorial design 部分要因試驗設計

作業&#xff1a; 1) A plot of data from a time series, which shows a cyclical pattern – please show a time series plot and identify the length of the major cycle. 2) Data from a full factorial or fractional factorial experiment with at least 2 factors –…

如何在Go中編寫防彈代碼:不會失敗的服務器工作流程

by Tal Kol通過塔爾科爾 如何在Go中編寫防彈代碼&#xff1a;不會失敗的服務器工作流程 (How to write bulletproof code in Go: a workflow for servers that can’t fail) From time to time you may find yourself facing a daunting task: building a server that really …

越獄第一至五季/全集迅雷下載

越獄 第一季 Prison Break Season 1 (2005) 本季看點&#xff1a;邁克爾斯科菲爾德是一頭陷于絕境欲拼死一搏的怒獅——他的哥哥林肯巴羅斯被認定犯有謀殺罪被投入了福克斯河監獄的死囚牢。雖然所有的證據都指出林肯就是兇手&#xff0c;邁克爾堅信兄長是無辜的。林肯的死刑執行…

leetcode面試題 16.19. 水域大小(深度優先搜索)

你有一個用于表示一片土地的整數矩陣land&#xff0c;該矩陣中每個點的值代表對應地點的海拔高度。若值為0則表示水域。由垂直、水平或對角連接的水域為池塘。池塘的大小是指相連接的水域的個數。編寫一個方法來計算矩陣中所有池塘的大小&#xff0c;返回值需要從小到大排序。 …

java -jar 默認參數_JAVA入門學習指南,建議收藏

如果你不懂Java 并且想認真學習接觸了解一下Java的語法&#xff0c;建議把這篇文章收藏了&#xff0c;多看幾遍&#xff0c;應該可以初步掌握Java 大部分基礎的語法 。 讓我們出發吧&#xff01;ps:本文有點長&#xff0c;耐心閱讀 。〇&#xff0c;編程環境工程項目推薦使用ID…

【RabbitMQ】 WorkQueues

消息分發 在【RabbitMQ】 HelloWorld中我們寫了發送/接收消息的程序。這次我們將創建一個Work Queue用來在多個消費者之間分配耗時任務。 Work Queues&#xff08;又稱為&#xff1a;Task Queues&#xff09;的主要思想是&#xff1a;盡可能的減少執行資源密集型任務時的等待時…

python matplotlib庫安裝出錯_使用pip install Matplotlib時出現內存錯誤

我使用的是Python2.7&#xff0c;如果我試圖安裝Matplotlib&#xff0c;如果我使用“pip install Matplotlib”&#xff0c;就會出現這個錯誤Exception:Traceback (most recent call last):File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line …

笑看職場什么程序員才搶手,什么樣的程序員漲薪多?

?程序員&#xff0c;怎么才算合格&#xff0c;不好說吧&#xff1b;他就像銷售一樣&#xff0c;一名銷售員&#xff0c;比如網絡銷售賣茶葉&#xff0c;他賣茶葉很厲害呀&#xff0c;可是你讓他去銷售房地產&#xff0c;就算他有點銷售的基礎&#xff0c;也要重新去學怎么銷售…

Android畫布Canvas裁剪clipRect,Kotlin

Android畫布Canvas裁剪clipRect&#xff0c;Kotlin private fun mydraw() {val originBmp BitmapFactory.decodeResource(resources, R.mipmap.pic).copy(Bitmap.Config.ARGB_8888, true)val newBmp Bitmap.createBitmap(originBmp.width, originBmp.height, Bitmap.Config.A…

調查|73%的公司正使用存在漏洞的超期服役設備

本文講的是調查&#xff5c;73%的公司正使用存在漏洞的超期服役設備&#xff0c;一份新近的調查覆蓋了北美350家機構的212000臺思科設備。結果顯示&#xff0c;73%的企業正在使用存在漏洞、超期服役的網絡設備。該數字在上一年僅為60%。 Softchoice公司思科部門業務主管大衛魏格…

為什么要做稀疏編碼_為什么我每天都要編碼一年,所以我也學到了什么,以及如何做。...

為什么要做稀疏編碼by Paul Rail由Paul Rail 為什么我每天都要編碼一年&#xff0c;所以我也學到了什么&#xff0c;以及如何做。 (Why I coded every day for a year, what I learned, and how you can do it, too.) I was looking to switch careers. The world today is no…

深度裝機大師一鍵重裝_筆記本怎么重裝系統?筆記本自己如何重裝系統?

如何給筆記本重裝系統呢?筆記本系統使用時間長了難免會運行緩慢&#xff0c;我們第一反應就是重裝系統筆記本了。但是很多小白用戶們就惆悵了&#xff0c;不知道筆記本怎么重裝系統&#xff0c;怎么進行重裝系統筆記本呢?首先&#xff0c;筆記本電腦可以重置系統&#xff0c;…

leetcode劍指 Offer 11. 旋轉數組的最小數字(二分查找)

把一個數組最開始的若干個元素搬到數組的末尾&#xff0c;我們稱之為數組的旋轉。輸入一個遞增排序的數組的一個旋轉&#xff0c;輸出旋轉數組的最小元素。例如&#xff0c;數組 [3,4,5,1,2] 為 [1,2,3,4,5] 的一個旋轉&#xff0c;該數組的最小值為1。 示例 1&#xff1a; 輸…

XMLHttpRequest狀態碼及相關事件

1.創建一個XMLHttpRequest對象 2.對XMLHttpRequest對象進行事件的監聽(定義監聽事件的位置不影響 3.對XMLHttpRequest對象的狀態碼 狀態 名稱描述0Uninitialized初始化狀態。XMLHttpRequest 對象已創建或已被 abort() 方法重置1Open open() 方法已調用&#xff0c;但是 send()…

-code vs 1474 十進制轉m進制

1474 十進制轉m進制 時間限制: 1 s空間限制: 128000 KB題目等級 : 白銀 Silver題解查看運行結果題目描述 Description將十進制數n轉換成m進制數 m<16 n<100 輸入描述 Input Description共一行 n和m 輸出描述 Output Description共一個數 表示n的m進制 樣例輸入 Sample In…

人工智能時代號角已吹響 COMPUTEX如何凝聚AI這股力量?

當前談到人工智能&#xff08;AI&#xff09;&#xff0c;或許大家最直接的反應是Google的AlphaGo&#xff0c;但比起“遙不可及”的圍棋機器人&#xff0c;其實AI早就融入人們生活&#xff0c;就像蘋果手機中的語音助手Siri&#xff0c;如此“平易近人”。從自動駕駛、機器人、…