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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值