WordPress Plugin Development Tutorial Manual - Metadata
Metadata is information about data, such as an image's size, type, creation time, dimensions, etc. In WordPress, metadata refers to additional information about posts, users, comments, and taxonomy items.
As an example, we create a custom post type of type "merchandise" that contains a price metadata field that is stored in the postmeta article metadata table.
WordPress primary data (posts, comments, users, taxonomy items) and their metadata are in a one-to-many relationship; one primary data can have many metadata, so we can store a lot of additional data in the metadata. This is where the flexibility of the WordPress data structure comes in.
In this section we'll discuss Managing Article Metadata. Customized metadata boxes, Rendering article metadata.
Managing article metadata
Add metadata
We can use the add_post_meta() function adds metadata that accepts a post_id, a meta_key, a meta_value, and a unique flag.
The meta_key is the basis for the plugin to refer to the meta_value elsewhere, we can use something like 'mycrazymetakeyname' or any other arbitrary string as the name, but to avoid conflicts and semantics it is recommended to prefix the name with an underscore separating the words in the name, e.g. wporg_featured_menu, and note that the same meta_key can be used multiple times to store a wide variety of metadata (see Unique Flags below).
The meta_value can be a string, integer, array or object. If meta_value is an array or object, WordPress will automatically serialize them before storing them in the database and deserialize them before fetching them from the database.
The unique flag allows us to declare whether a piece of metadata is unique with respect to a piece of master data. A non-unique meta_key can have more than one value with respect to a piece of master data, for example, the meta_key 'price', the price of a product is unique so we should add the unique flag to this metadata to ensure that there is only one price for a product. data, so we should add the unique tag to this metadata to ensure that there is only one price for a product.
Updating metadata
If we need to update a piece of metadata that already exists, we can use the update_post_meta(), if we use this function to update a piece of metadata that doesn't exist, the function automatically calls add_post_meta() to add that piece of data for us, with the same arguments as the add_post_meta() Same.
Delete metadata
If we need to delete a piece of metadata, use the delete_post_meta() function that accepts a post_id, a meta_key, and an optional meta_value.
character escaping
WordPress stores post metadata using the stripslashes() Some strings in the data are escaped, so care needs to be taken when passing in strings that may contain \ escaped strings (e.g. JSON). For example, a JSON string {key:value with \escaped quotes\}
::
$escaped_json = '{key:value with \escaped quotes\}';
update_post_meta($id, 'escaped_json', $escaped_json);
$broken = get_post_meta($id, 'escaped_json', true);
/*
$broken, after stripslashes(), ends up unparsable.
{key:value with escaped quotes}
*/
method settle an issue
By using the function wp_slash() (introduced in WordPress 3.6) to add an escape level to compensate for stripslashes() escaping.
$escaped_json = '{key:value with \escaped quotes\}';
update_post_meta($id, 'double_escaped_json', wp_slash($escaped_json));
$fixed = get_post_meta($id, 'double_escaped_json', true);
/*
$fixed, after stripslashes(), ends up as desired.
{key:value with \escaped quotes\}
*/
Hidden Custom Fields
If we intend to use a custom field to store data in a plugin or theme, it is important to note that WordPress does not display the meta_key starting with an underscore "_" in the custom field edit cleanup. we can use the add_meta_box() function to add metadata boxes to display these hidden custom fields.
The following example will add a hidden custom field with a meta_key of "_color" and a value of "red", which will not be displayed in the WordPress default custom field editing screen.
add_post_meta( 68, '_color', 'red', true );
Hidden arrays
In addition, if meta_value is an array, this metadata will not be displayed on the custom field editing screen even if meta_key is not underlined. Because the data stored in the database is escaped, it is difficult to edit a piece of escaped data.
Customized metadata boxes
What is a metadata box
When a user edits a post, the editing interface consists of several default boxes: editor, publish, taxonomy, tags, etc. These are all metadata boxes. Themes and plugins can also add custom metadata boxes to any post type editing interface. The content of the custom metadata box is usually an HTML form element through which the user enters the data required by the theme or plugin. In addition to the form, the content of the metadata box can also be any HTML we need.
Why use metadata boxes?
Metadata boxes are convenient and flexible modular article data editing elements that allow users to easily edit the relevant information of the current article. Our custom metadata boxes and the default article information are displayed in one interface, with clear subordination and correlation between them.
If users don't need a particular metadata box, they can easily hide it, and as needed, users can also sort the metadata boxes to put the ones they use frequently in the right place.
Add metadata box
If we need to create a metadata box, call the add_meta_box() function and mount the function that executes that call to the add_meta_boxes
Action hook is sufficient. The following example adds a metadata box to the article and wporg_cpt custom article type editing screens.
function wporg_add_custom_box() {
$screens = ['post', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Custom Meta Box Title', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen // Post type
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box'); }
The wporg_custom_box_html above is a callback function to display the HTML form needed for the metadata box, the sample code for this function is as follows:
function wporg_custom_box_html($post) {
? .
The above example only packages a drop-down list of fields , in the actual development , we can add any type of form fields as needed , if you need to add a lot of fields , you can consider the data in accordance with the similarity of these fields grouped , which can make the interface more clear and easy to use .
Getting custom field values as form defaults
If we have saved the custom field, when displaying the form, we need to display the saved value as the default value of the form along with the form, we can use the get_post_meta() function to get this value. The following example adds the selected status to the dropdown selection form using the value of the custom form.
function wporg_custom_box_html($post) {
$value = get_post_meta($post->ID, '_wporg_meta_key', true); ?
? >
In the above code, selected() is a very useful helper function to help us set the data of the selected option, please refer to the detailed introduction of this function: Documentation for the selected() functionThe
Save custom field values
When we save or update a post, several Actions are triggered, and we can save the value entered in the custom field when any of the Actions are triggered as needed. In this example, we use the save_post Action hook, and depending on the situation, sometimes other hooks may be more appropriate. Note that save_post may be triggered multiple times when updating a post, and we need to take care of this when saving data.
We can save the input data anywhere, even outside of WordPress, and since we're dealing with data related to WordPress posts, saving it in post_meta is a good option in most cases.
The following example stores the wporg_field data passed by the topic when saving the post into the hidden post_meta _key.
function wporg_save_postdata($post_id) {
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
}
}
add_action('save_post', 'wporg_save_postdata');
The sample code above does not do the necessary security checks, which should never be forgotten in the actual code.
What happens behind the scenes
We don't usually need to care about what happens behind the scenes, so for the sake of completeness of content, here's a brief explanation.
When WordPress displays the post editing screen, it calls the do_meta_boxes() The function iterates through all the metadata boxes and calls the function specified by the callback parameter in the metadata box to display the form, adding the required tags (such as div titles, etc.) before displaying the contents of the form.
Remove metadata box
If we need to remove an existing metadata box from the edit screen, we can use the remove_meta_box() function, the passed parameters need to be exactly the same as the corresponding parameters when adding the metadata box. If you need to remove the default metadata box, you can check the wp-includes/edit-form-advanced.php file for the code to add the default metadata box to get the required parameters.
Other implementations
So far we've been using a procedural-oriented approach to adding metadata boxes, and there are other programming methods we can use to add them.
object-oriented
Adding metadata boxes using an object-oriented approach is very simple and we don't have to worry about naming conflicts in the global namespace. To save memory and make the implementation simpler, the following example uses an abstract class with static methods.
abstract class WPOrg_Meta_Box {
public static function add() {
$screens = ['post', 'wporg_cpt']; foreach ($screens as $screen) { $screens as $screen
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Custom Meta Box Title', // Box title
[self::class, 'html'], // Content callback, must be of type callable
$screen // Post type
);
}
}
public static function save($post_id) {
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
}
}
public static function html($post) {
$value = get_post_meta($post->ID, '_wporg_meta_key', true); ?
? >
Ajax
Since the HTML element of the metadata box is located within the form for editing the article, by default the data inside the metadata box is stored with the article data and submitted in the $_POST super variable when the article is saved. As needed, we can use AJAX to enhance the user experience by allowing the data inside the metadata box to be submitted separately, regardless of whether the user saves the post or not.
Defining a Trigger
First, we need to define a trigger event, which can be every link clicked, a value changed, or any other JavaScript event. In the following example, we'll define change as the event that triggers the execution of the Ajax request.
(function ($, window, document) {
'use strict';
// execute when the DOM is ready
$(document).ready(function () {
// js 'change' event triggered on the wporg_field form field
$('#wporg_field').on('change', function () {
// our code
}); })
});
}(jQuery, window, document)).
Client Code
Next, we need to define the trigger, which means we need to write the AJAX client code. In the following example, we will initiate a POST request, and the server will respond with a success or failure to determine if the wporg_field is valid.
(function ($, window, document) {
'use strict';
// execute when the DOM is ready
$(document).ready(function () {
// js 'change' event triggered on the wporg_field form field
$('#wporg_field').on('change', function () {
// jQuery post method, a shorthand for $.ajax with POST
$.post(wporg_meta_box_obj.url, // or ajaxurl
{
action: 'wporg_ajax_change', // POST data, action
wporg_field_value: $('#wporg_field').val() // POST data, wporg_field_value
}, function (data) {
// handle response data
if (data === 'success') {
// perform our success logic
} else if (data === 'failure') {
// perform our failure logic
} else {
// do nothing
}
}
); });
}); })
}); }
}(jQuery, window, document)).
Next, we will create a custom JavaScript object called wporg_meta_box_obj that contains the URL for customizing the WrodPress AJAX action.
Insert client code
In order for the code in the previous step to access the JavaScript object wporg_meta_box_obj, we need to add this object to the front-end code. In the following example, we have added AJAX functionality to the editing interface of two article types: article and wporg_cpt.
The path where the JacaScript files are located is/plugin-name/admin/meta-boxes/js/admin.js
(math.) genusplugin-name
is the plugin folder.
function wporg_meta_box_scripts(){
// get current admin screen, or null
$screen = get_current_screen(); // verify admin screen object.
// verify admin screen object
if (is_object($screen)) {
// enqueue only for specific post types
if (in_array($screen->post_type, ['post', 'wporg_cpt'])) {
// enqueue script
wp_enqueue_script('wporg_meta_box_script', plugin_dir_url(__FILE__) . 'admin/meta-boxes/js/admin.js', ['jquery']); // Localize script, create a custom script.
// localize script, create a custom js object
wp_localize_script(
'wporg_meta_box_script',
'wporg_meta_box_obj',
[
'url' => admin_url('admin-ajax.php'), [
]
);
}
}
}
add_action('admin_enqueue_scripts', 'wporg_meta_box_scripts');
Server-side code
The final step is to write the server-side code that handles the AJAX request.
function wporg_meta_box_ajax_handler() {
if (isset($_POST['wporg_field_value'])) {
switch ($_POST['wporg_field_value']) {
case 'something'.
echo 'success';
break;
default: echo 'failure'; break; }
echo 'failure'; break; default.
break; default: echo 'failure'; break
}
}
// ajax handlers must die
die; }
}
// wp_ajax_ is the prefix, wporg_ajax_change is the action we've used in client side code
add_action('wp_ajax_wporg_ajax_change', 'wporg_meta_box_ajax_handler'); // ajax handlers must die; } // wp_ajax_ is the prefix, wporg_ajax_change is the action we've used in client side code
As another reminder, the sample code on this page lacks enough security operations to be safe, be sure to add the security code in the actual code.
For more information about AJAX, see the AJAX Chapter respond in singing Ajax DocumentationThe
More information
- Complex Metadata Boxes in WordPress
- How to Create Custom Post Metadata Boxes in WordPress
- Comprehensive Developer's Guide to WordPress Metadata Boxes
Rendering article metadata
WordPress provides two functions to help us access the data stored in the postmeta table get_post_meta()(math.) genusget_post_custom()The
get_post_meta
function to get the data of a meta_key of a specified article, using the following method.
get_post_meta(
int $post_id,
string $key = '',
bool $single = false
);
Example:
$wporg_meta_value = get_post_meta(get_the_ID(), 'wporg_meta_key');
get_post_custom
Get all the metadata for a particular article, using the following method:
get_post_custom(
int $post_id
);
Example:
$meta_array = get_post_custom(get_the_ID());