In the first article of this series, I gave an overview of all the various types of metadata provided by WordPress, where the metadata is saved, and what we will cover in this series.
Additionally, I define what metadata is; its role in WordPress, and how it relates to us as developers. But that's the purpose of the introduction: a survey of what we'll cover in the rest of this series.
Starting with this article, we will start exploring the WordPress Post Meta API, understanding why it is useful, what we can do with it, and how to take advantage of the methods provided through the WordPress application.
First of all, if you are an advanced developer, this series of tutorials is unlikely to be of much help to you. Instead, it's more suitable for those who have done some work on the theme, maybe tweaked some plugin code, and are ready to go a step further by adding some extra information to the posts (or post types) that make up their project.
Secondly, please note that the code examples in this tutorial are not intended for use in a production environment. Instead, the code we're looking at is not intended for use anywhere where the site is publicly accessible to anyone.
Now, I plan to cover more advanced techniques on this topic after completing this series. But for now, we're only concerned with API usage.
why? What is the delay in reporting extensions? Simply put, it has to do with website security. Specifically, whenever we write information to a database, we must assume that the data is stored in an insecure format; we must sanitize the data.
We need to explore a completely different set of APIs for cleaning data that will be used in conjunction with the metadata API, but this is not a tutorial for doing so.
I know, talking about these APIs and not being able to take advantage of them might sound a little frustrating. But remember, this is just an introduction to the API. These tutorials should give you enough information to start using post metadata on your computer, but should also leave you with enough questions so that we can explore the topic in more depth in a future series of articles.
With that said, let’s go ahead and start using the WordPress Post Meta API. Please note: this is a long tutorial.
Before we look at the code, it’s important to make sure you have the necessary tools to browse the database running your WordPress installation. Some of the tools available include:
But feel free to use whatever you like best. As long as you can view the data in the database, you're good to go.
Next, let’s understand how WordPress defines post metadata. According to Codex:
WordPress has the ability to allow post authors to assign custom fields to posts. This arbitrary extra information is called metadata.Metadata is processed via key/value pairs. The key is the name of the metadata element. This value is the information that will appear in the metadata list for each post associated with that information.
Simply put, WordPress allows us to write custom information to the database, associate it with any post we want, and then retrieve it as needed. Additionally, information is stored using unique key/value pairs.
If this is new to you, don't worry. The idea is that for each value you store, it is associated with a unique key (just like a doorknob has a unique key that is used to unlock it).
The key is how we retrieve the value from the post. But it does raise a question: What happens if an article has multiple metadata associated with it? That is, if any given post can store multiple metadata simultaneously, how do we retrieve unique metadata?
When we start looking at some of the example code below, we'll see that in addition to using the key used when storing the data, we also need to pass the unique ID of the post to the function.
But nothing beats seeing it in action. So, assuming you have WordPress set up on your local machine and can edit functions.php
in the core of the default theme, let’s get started.
I will use the following tools:
The most important thing is that you are running WordPress and the theme mentioned above.
Finally, if you prefer other IDEs and database front-ends, that's totally fine.
We covered a lot of information in the introduction to this article, but this information will come in handy when we start looking at not only the Post Meta API but other APIs as well. So keep this mentality. I will also refer to this article in a future article.
Let’s delve into the API.
The way we merged the code is not a professional way to change the theme, implement this feature, or interact with the API. We do this as a first step into WordPress development for beginners.
In subsequent series, we will extract the work done in this series into a more maintainable plug-in that also pays more attention to maintainability, security, etc.
Currently, we are focusing on the basics of the API.
Remember that I'm using a basic installation of WordPress along with Twenty Six Themes for the demos that we're going to see throughout this tutorial and the rest of the tutorials in the series.
Second, we will make changes in functions.php
. This is generally not the best place to make this change; however, make sure you read the note above before proceeding.
That being said, we assume your server is running, your IDE is up and ready, and functions.php
already exists in the editor. While your screenshot may look a little different, it should look similar to:
The challenge with using functions.php
is that it is already filled with code that helps enhance the functionality of an existing theme. Although we will eventually move the code into a plugin in a future series, we want to at least take the first step of making a file so that we can include our code independently.
Use the IDE of your choice:
tutsplus-metadata.php
. When finished, you should have the following on your file system:
Finally, we need to make sure we include it in functions.php
. To do this, add the following lines of code under the PHP start tag.
<?php include_once( 'tutsplus-metadata.php' );
Reload your browser. If all goes well, you should see the exact same theme as you did before adding the file to functions.php
.
Now, let's get to work.
Recall our previous discussion, we need three things to add metadata to the database:
In this tutorial, all we have to do is add metadata that will appear in the default Hello World! that comes standard with every WordPress installation. in the post.
Let's say we want to add some metadata containing our name. So the meta key we will use is my_name
and the value we will use is your name. In my case, it's "Tom McFarlin."
The first thing we need to do is define a function that hooks into the_content
. This will allow us to output text while the function is running. If you're new to hooks, read this series.
Your initial code should look like this:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { echo "[We are here.]" } return $content; }
When you execute this code, the string "[We are here.]" should appear above the post content and before other content, and it should only appear on Hello World! post. This is because we check to make sure the ID is 1 before the echo
string.
Please note that the final version of the code shared at the end of this article will contain comments. Until then, I'll explain what the code is doing as we add each new section to it.
Now let's add some actual metadata. To do this, add this code to the body of the condition so we know for sure that we are doing this for Hello World. Since we already checked for ID 1 in the condition, we can delete the code we added in the previous section and update it.
In the body of the conditional statement, we will call the add_post_meta
API function as follows:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { add_post_meta( get_the_ID(), 'my_name', 'Tom McFarlin' ); } return $content; }
It would be great if we could do something with this information. Before that happens, though, we need to know more. That said, there are some nuances about updating metadata (and how it differs from adding metadata) and some that you might not have thought of when dealing with APIs.
There is a subtle difference between adding metadata and updating metadata. Do you know how a key uniquely identifies the value associated with it? Well, that's partially accurate.
When you call add_post_meta
, an entry is created each time you make that call. So in our code above, if we refresh the page three times, then you will see something like this:
Very curious, right? Recall the contents of the code:
请注意,如果指定帖子的自定义字段中已存在给定键,则会添加具有相同键的另一个自定义字段,除非 $unique 参数设置为 true,在这种情况下,不会进行任何更改。
啊,该函数接受一个可选参数。这是一个名为 $unique
的布尔值,如果我们只想确保添加的值是唯一的,它允许我们传递 true
。
此时您可能想要删除现有记录。如果没有,也没关系,只需为 my_name
键使用不同的值即可。
这意味着我们可以将代码更新为如下所示:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { add_post_meta( get_the_ID(), 'my_name', 'Tom McFarlin', true ); } return $content; }
现在您只创建一个条目。此外,如果您尝试更改代码中该键的值,那么它在数据库中将不会被覆盖。。一旦写入帖子元数据完成,它就会像第一次一样存储。
但事实并非一定如此,这就是 update_post_meta
发挥作用的地方。事实上,update_post_meta
可能比 add_post_meta
更常用,具体取决于您的用例。
在查看代码之前,请先查看 Codex 的内容:
函数 update_post_meta() 更新指定帖子的现有元键(自定义字段)的值。这可以用来代替 add_post_meta() 函数。该函数要做的第一件事是确保 $meta_key 已经存在于 $post_id 上。如果没有,则调用 add_post_meta($post_id, $meta_key, $meta_value) 并返回其结果。
你明白了吗?它可以“用来代替 add_post_meta
”,这很有用,因为这意味着:
update_post_meta
,此时,您可能想要删除数据库中的信息,或创建一对新的键和值。这意味着我们可以将代码更新为如下所示:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { update_post_meta( get_the_ID(), 'my_name', 'Tom McFarlin' ); } return $content; }
不过,这也带来了一些固有的危险。
也就是说,如果您覆盖了一个您从未打算覆盖的值,那么该值就会消失,并且无法回收(除非您做了超出本系列范围的更出色的工作)。
不过, update_post_meta
有一个可选的最后一个参数,那就是 $prev_value
参数。也就是说,您可以指定要覆盖哪个值。
例如,您有使用 add_post_meta
创建的具有相同密钥的多条记录,并且您只想更新其中一条记录。要更新该数据,您需要传入与该一条记录对应的值。
add_post_meta
和 update_post_meta
之间的区别可能被认为很微妙,但这取决于您的用例。
在这里,我将尝试尽可能简单地分解它们,因为尽管考虑到我们上面看到的示例,它可能看起来很复杂,但当您将其全部展开时,它会更简单。
add_post_meta
非常有用。如果该值已经存在,则可能会或不会写入新值。如果您为函数的 $unique
参数传递 true
,则只会创建第一条记录,并且不会覆盖该 >除了 update_post_meta
。update_post_meta
可以用来代替 add_post_meta
并且将始终覆盖以前存在的值。如果您正在处理由 add_post_meta
创建的多条记录,那么您可能需要指定要覆盖的先前值。这就是一切。当然,我们仍然需要处理从数据库中检索记录并将其显示在屏幕上的问题。
在检索帖子元数据时,您需要记住两件事:
有时这取决于您存储原始信息的方式;有时它取决于您想要如何使用它。
在了解检索信息的各种方法之前,让我们首先了解一下执行此操作的基本 API 调用。具体来说,我说的是 get_post_meta
。如果您到目前为止一直在关注,那么理解 API 应该相对容易。
该函数接受三个参数:
来自法典:
检索帖子的帖子元字段。如果 $single 为 false,则将是一个数组。如果 $single 为 true,则为元数据字段的值。
看起来很简单。因此,考虑到我们源代码的最后一部分现在所在的位置,我想说我们可以通过调用 get_post_meta( get_the_ID(), 'my_name' );
来检索信息。 p>
上面的代码将返回一个数组。
每当您听到“多个值”这个短语时,想象一下您正在使用的编程语言中的数组或某种类型的数据集合会很有帮助。
在我们的示例中,考虑一下我们使用 add_post_meta
多次存储相同密钥的情况。作为回顾,数据库如下所示:
如果我通过密钥检索信息,我会得到什么?由于我没有指定我想要一个字符串,因此我将返回所有记录的数组。这将使我能够迭代它们中的每一个。
另一方面,如果我指定 true 来获取字符串,那么我只会获取使用 add_post_meta
创建的第一行。
为此,如果您希望获取给定键的多个值,那么您的代码将如下所示:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { var_dump( get_post_meta( get_the_ID(), 'my_name' ) ); } return $content; }
请注意,我使用 var_dump
是为了更轻松地在浏览器中查看从 WordPress 返回的信息;然而,我更喜欢使用调试器,我们可能会在以后的文章中讨论这一点。
现在假设您想要为一篇文章存储单个值。在这种情况下,您仍然需要帖子 ID 和元数据密钥;但是,您还需要提供 true
作为 get_post_meta
的第三个参数。
如上所述,如果您正在处理使用 add_post_meta
创建多行的情况,那么您将取回创建的第一行;但是,如果您将此函数与 update_post_meta
一起使用,那么您将返回存储的数据的字符串值。
由于我们已经介绍了前者但没有介绍后者,所以代码如下:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { var_dump( get_post_meta( get_the_ID(), 'my_name', true ) ); } return $content; }
然后,您将在调用该函数时返回您保存为元值的任何值。与必须使用一组可能包含也可能不包含类似信息的记录和数组相比,这非常简单。
使用帖子元数据的最后一点与删除它有关。这很简单,但我们需要了解一些细微差别,以确保我们有效地做到这一点。
但首先,这是 Codex 的定义:
此函数从指定帖子中删除具有指定键或键和值的所有自定义字段。
简短、甜蜜、切中要点。该函数接受三个参数:
meta 值是可选的,但如果您一直在使用 add_post_meta
并希望删除多次调用该函数创建的特定条目之一(正如我们已经在本教程的其他地方可以看到)。
虽然调用 delete_post_meta
就像传递帖子 ID、元键和可选元值一样简单,但该函数返回一个布尔值,说明数据是否已删除。
删除我们迄今为止一直在查看的一些帖子元数据的示例代码可能如下所示:
<?php add_filter( 'the_content', 'tutsplus_metadata' ); function tutsplus_metadata( $content ) { if ( 1 === get_the_ID() ) { delete_post_meta( get_the_ID(), 'my_name' ); } return $content; }
但是,您的实施可能会有所不同。如果您正在使用多个元数据,并且想要验证删除是否成功,那么您可以将代码包装在条件中。
下面您将找到一个很长的、有记录的代码片段,它应该代表我们在本教程中讨论的大部分内容。请注意,这些函数挂接到 the_content
。
这仅用于演示目的,以便您可以在加载特定页面时轻松触发这些函数。
<?php /** * This file shows how to work with the common Post Meta API functions. * * Namely, it demonstrates how to use: * - add_post_meta * - update_post_meta * - get_post_meta * - delete_post_meta * * Each function is hooked to 'the_content' so that line will need to be * commented out depending on which action you really want to test. * * Also note, from the tutorial linked below, that this file is used form * demonstration purposes only and should not be used in a production * environment. * * Tutorial: * http://code.tutsplus.com/tutorials/how-to-work-with-wordpress-post-metadata--cms-25715 * * @version 1.0.0 * @author Tom McFarlin * @package tutsplus_wp_metadata */ add_filter( 'the_content', 'tutsplus_add_post_meta' ); /** * Determines if the current post is the default 'Hello World' post and, if so, * adds my name as the post meta data to the postmeta database table. * * @param string $content The post content. * @return string $content The post content. */ function tutsplus_add_post_meta( $content ) { if ( 1 === get_the_ID() ) { add_post_meta( get_the_ID(), 'my_name', 'Tom McFarlin' ); } return $content; } add_filter( 'the_content', 'tutsplus_update_post_meta' ); /** * Determines if the current post is the default 'Hello World' post and, if so, * updates my name as the post meta data to the postmeta database table. This * is an alternative way of writing post metadata to the postmeta table as * discussed in the linked tutorial. * * @param string $content The post content. * @return string $content The post content. */ function tutsplus_update_post_meta( $content ) { if ( 1 === get_the_ID() ) { update_post_meta( get_the_ID(), 'my_name', 'Tom McFarlin' ); } return $content; } add_filter( 'the_content', 'tutsplus_get_post_meta' ); /** * Determines if the current post is the default 'Hello World' post and, if so, * retrieves the value for the 'my_name' in the format of a string and echoes * it back to the browser. * * @param string $content The post content. * @return string $content The post content. */ function tutsplus_get_post_meta( $content ) { // Note: Don't worry about the esc_textarea call right now. if ( 1 === get_the_ID() ) { echo esc_textarea( get_post_meta( get_the_ID(), 'my_name', true ) ); } return $content; } add_filter( 'the_content', 'tutsplus_delete_post_meta' ); /** * Determines if the current post is the default 'Hello World' post and, if so, * deletes the post metadata identified by the unique key. * * @param string $content The post content. * @return string $content The post content. */ function tutsplus_delete_post_meta( $content ) { if ( 1 === get_the_ID() ) { delete_post_meta( get_the_ID(), 'my_name' ); } return $content; }
通常,您会发现与其他挂钩相关的元数据函数,例如 save_post
和类似操作,但这是更高级工作的主题。也许我们会在今年晚些时候的另一个系列中介绍这一点。
WordPress Codex 中提供了每个 API 函数,因此,如果您想在本系列的下一篇文章之前跳到前面并进行更多阅读,那么请随意这样做。
如前所述,这是对 WordPress Post Meta API 的介绍。通过 Codex、本教程以及提供的源代码中提供的信息,您应该能够开始向与您的每篇帖子相关的数据库写入其他内容。
但请记住,这只是为了演示目的,因为我们有更多信息要介绍。具体来说,我们需要检查数据清理和数据验证。尽管我们首先要讨论其他主题(例如用户元数据、评论元数据等),但我们很快就会讨论更高级的主题。
Ultimately, we try to lay the foundation for future WordPress developers to go on to develop solutions for others, for their institutions, and even for their projects.
Having said that, I'm looking forward to continuing this series. Remember, if you’re just getting started, you can check out my series on How to Get Started with WordPress , which focuses on themes specifically for WordPress beginners.
In the meantime, if you’re looking for other utilities to help you build your growing WordPress toolset, or to learn code and become more proficient at WordPress, don’t forget to check out what we have available for purchase on the Envato Marketplace.
Remember you can view all my courses and tutorials on my profile page and you can follow me on my blog and/or Twitter (@tommcfarlin) where I discuss various software development Practices and how we use them in WordPress.
Please feel free to leave any questions or comments in the feed below and I will do my best to respond to each one.
The above is the detailed content of Use WordPress post metadata effectively. For more information, please follow other related articles on the PHP Chinese website!