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' => t
rue makes the custom post type accessible via the REST API'show_in_rest' => t
rue可以通過REST API訪問自定義帖子類型'rest_base' => 'produc
ts' 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_filter
和rest_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