接着上篇继续,上篇简单介绍了什么是Meta Data,这篇说说如何调用Meta Data,还没有翻译完,待更新
WordPress 提供了各种各样的方法来获取文章 meta data。
我们可以通过 get_post_meta() 标明某个域来获取某一个 meta data, 比如说, 在当前文章循环里获取一个叫 ‘foo’ 的自定义域,我们可以这样获取:
get_post_meta( get_the_id(), 'foo', true );
请注意我们把最后的参数设为 true。这个参数叫做 “single”,它 决定了我们是否需要一个单一的值或者返回包含多个值的数组。 也就是我们可以从一个变量里获取一个文章的所有自定义段的值或者一个自定义段的所有的值。
Sometimes we want to build an entire loop around a meta data, and this is where WP_Query is very useful. WP_Query allows us to do what is called a “meta query” where we query the posts based on one or more meta fields, and return the posts that have values that match a specific value. The result is a collection through which we can loop.
For example, imagine we have a field called “author_name” and we wanted to return every post where the field author_name had the value value ‘J.R.R. Tolkien’. WP_Query allows us to do this easily – we’ll be taking a look at this in-depth during the fourth part of this series.
Posts are not the only type of data that has meta data. For example, you know all of those fields that are available in the user profile? Those are all meta fields, instead of being stored in the wp_postmeta table, they are stored in the wp_usermeta table.
As a result, we have special functions and classes for user meta information. The functions get_user_meta() and get_author_meta() are the equivalent of get post meta for users. WP_Query also has its own users equivalent – WP_User_Query.
When you use functions like get_post_meta() to return more than one field, you will likely get what is called a multi-dimensional array. A multi-dimensional array is also known as an array of arrays. Each array within the multi-dimensional array could be a multi-dimensional array.
Sound confusing? Don’t worry! In this series, we are going to cover how to read multi-dimensional arrays in order to “drill-down” to the index you need.
Finally – as we mentioned earlier – another method for getting information about a post is to use WP_Query. When you use the WP_Query class you are using what is called object-oriented PHP and what you return is different than an array – it’s an object.
In some ways objects are similar to arrays in that they may contain arrays of information. But with an object you can use any of the functions available on class. This means that not only can we use a WP_Query object to return a value for a meta field, but we can also use its internal methods, the most common of which is the_post().
At this point, we’ve taken a survey of the various types of meta data, how they are stored, how they can be represented, and how to retrieve them.
As we continue with this series, we’ll take a much deeper look at each aspect of the meta data tables, the associated APIs, and how we can leverage them to introduce functionality and flexibility into our projects.
原文链接:http://code.tutsplus.com/articles/mastering-wordpress-meta-data-an-introduction-to-meta-data–wp-34547