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.mzph.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;如此“平易近人”。从自动驾驶、机器人、…