将自定义元框添加到WordPress管理界面

tech2022-12-28  116

WordPress lets us add custom meta boxes to posts, pages and custom post types via the admin interface. WordPress also provides APIs to customize the default meta boxes.

WordPress允许我们通过管理界面将自定义元框添加到帖子,页面和自定义帖子类型。 WordPress还提供了用于自定义默认元框的API。

In this tutorial, I will show you how to add new custom meta boxes, save custom meta data, validate meta data, retrieve custom meta data on the front end and also remove the default meta boxes.

在本教程中,我将向您展示如何添加新的自定义元框,保存自定义元数据,验证元数据,在前端检索自定义元数据以及如何删除默认的元框。

什么是自定义元框? (What is a Custom Meta Box?)

Custom meta boxes allow users to add additional information to posts, pages and custom post types, apart from the default set of information that WordPress takes using default meta boxes. Plugins and Themes can use custom meta boxes to take additional structured user input.

自定义meta框使用户可以将附加信息添加到帖子,页面和自定义帖子类型中,除了WordPress使用默认meta框获取的默认信息集。 插件和主题可以使用自定义元框来接受其他结构化的用户输入。

Custom meta boxes can also be added to the dashboard and attached to the admin interface. WordPress dashboard widgets are actually meta boxes.

自定义元框也可以添加到仪表板并附加到管理界面。 WordPress仪表板小部件实际上是元框。

In addition to the meta boxes, you can also edit the contents and appearance of the Admin Bar that is seen by those who are logged in to the admin interface.

除了meta框外,您还可以编辑登录到管理界面的人员看到的管理栏的内容和外观 。

Editor, Custom Fields, Featured Image, Categories, and Tags on a post, page or custom post page admin interface are default meta boxes. They are created by the WordPress core.

帖子,页面或自定义帖子页面管理界面上的编辑器,自定义字段,特色图像,类别和标签是默认的元框。 它们是由WordPress核心创建的。

自定义元框与自定义字段 (Custom Meta Box vs Custom Fields)

Custom fields allow users to add key/value pairs of data to a post, page or custom post type. But meta boxes can have many varieties of input fields such as color picker, file upload, drop downs, and so on.

自定义字段允许用户将键/值数据对添加到帖子,页面或自定义帖子类型。 但是,元框可以具有多种输入字段,例如颜色选择器,文件上传,下拉列表等。

什么是元数据? (What is Meta Data?)

Meta Data are values of the form fields embedded in Custom Meta Boxes. WordPress stores them as key/value pairs, such as meta key and meta value. Meta key is the name of the form field and meta value is the form field value.

元数据是嵌入在“自定义元框”中的表单字段的值。 WordPress将它们存储为键/值对,例如元键和元值。 Meta键是表单字段的名称,而meta值是表单字段的值。

创建一个元框 (Creating a Meta Box)

add_meta_box function is used to create custom meta boxes. This function is only responsible for registering and displaying custom meta boxes.

add_meta_box函数用于创建自定义元框。 此功能仅负责注册和显示自定义元框。

Here is the code to add a custom meta box to WordPress posts:

这是将自定义元框添加到WordPress帖子的代码:

function custom_meta_box_markup() { } function add_custom_meta_box() { add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_markup", "post", "side", "high", null); } add_action("add_meta_boxes", "add_custom_meta_box");

add_meta_box should be called inside add_meta_boxes hook.

add_meta_box应内部被称为add_meta_boxes挂钩。

add_meta_box takes 7 arguments. Here are the list of arguments:

add_meta_box接受7个参数。 以下是参数列表:

$id: Every meta box is identified by WordPress uniquely using its id. Provide an id and remember to prefix it to prevent overriding.

$ id :每个meta框由WordPress唯一地使用其id标识。 提供一个ID,并记住给它加上前缀以防止覆盖。

$title: Title of the meta box on the admin interface.

$ title :管理界面上的meta框的标题。

$callback: add_meta_box calls the callback to display the contents of the custom meta box.

$ callback : add_meta_box调用回调以显示自定义元框的内容。

$screen: Its used to instruct WordPress in which screen to display the meta box. Possible values are "post", "page", "dashboard", "link", "attachment" or "custom_post_type" id. In the above example we are adding the custom meta box to WordPress posts screen.

$ screen :用于指示WordPress在哪个屏幕上显示meta框。 可能的值为"post" , "page" , "dashboard" , "link" , "attachment"或"custom_post_type" id。 在上面的示例中,我们将自定义元框添加到WordPress帖子屏幕。

$context: Its used to provide the position of the custom meta on the display screen. Possible values are "normal", "advanced" and "side". In the above example we positioned the meta box on side.

$ context :用于提供自定义元在显示屏上的位置。 可能的值为"normal" , "advanced"和"side" 。 在上面的示例中,我们将meta框放在一边。

$priority: Its used to provide the position of the box in the provided context. Possible values are "high", "core", "default", and "low". In the above example we positioned the meta box

$ priority :用于在提供的上下文中提供框的位置。 可能的值为"high" , "core" , "default"和"low" 。 在上面的示例中,我们放置了元框

$callback_args: Its used to provide arguments to the callback function.

$ callback_args :用于为回调函数提供参数。

Here is how the meta box looks:

这是meta框的外观:

Here, the custom meta box content is empty because we haven’t yet populated the content.

在这里,自定义元框内容为空,因为我们尚未填充该内容。

在自定义元框中显示字段 (Displaying Fields in a Custom Meta Box)

For demonstration purpose I will add a text input, drop down and a checkbox form field to the custom meta box.

出于演示目的,我将在自定义元框中添加文本输入,下拉列表和复选框表单字段。

Here is the code:

这是代码:

function custom_meta_box_markup($object) { wp_nonce_field(basename(__FILE__), "meta-box-nonce"); ?> <div> <label for="meta-box-text">Text</label> <input name="meta-box-text" type="text" value="<?php echo get_post_meta($object->ID, "meta-box-text", true); ?>"> <br> <label for="meta-box-dropdown">Dropdown</label> <select name="meta-box-dropdown"> <?php $option_values = array(1, 2, 3); foreach($option_values as $key => $value) { if($value == get_post_meta($object->ID, "meta-box-dropdown", true)) { ?> <option selected><?php echo $value; ?></option> <?php } else { ?> <option><?php echo $value; ?></option> <?php } } ?> </select> <br> <label for="meta-box-checkbox">Check Box</label> <?php $checkbox_value = get_post_meta($object->ID, "meta-box-checkbox", true); if($checkbox_value == "") { ?> <input name="meta-box-checkbox" type="checkbox" value="true"> <?php } else if($checkbox_value == "true") { ?> <input name="meta-box-checkbox" type="checkbox" value="true" checked> <?php } ?> </div> <?php }

Here is how the code works:

代码的工作方式如下:

First we set the nonce field so that we can prevent CSRF attack when the form is submitted.

首先,我们设置随机数字段,以便在提交表单时可以防止CSRF攻击。

get_post_meta is used to retrieve meta data from the database. If no such meta data is present, it returns an empty string. If your user has already submitted the form earlier, then we use the meta data stored in database. Otherwise, we switch to the default value.

get_post_meta用于从数据库检索元数据。 如果没有这样的元数据,它将返回一个空字符串。 如果您的用户已经提前提交了表单,那么我们将使用存储在数据库中的元数据。 否则,我们切换到默认值。

Here is how the meta box looks now:

这是meta框现在的外观:

存储元数据 (Storing Meta Data)

Now we need to store the custom meta data when a user submits the form; need to save the post.

现在,当用户提交表单时,我们需要存储自定义元数据; 需要保存帖子。

Here is the code to save meta data when a user clicks on the ‘save draft’ or ‘publish’ button:

这是当用户单击“保存草稿”或“发布”按钮时保存元数据的代码:

function save_custom_meta_box($post_id, $post, $update) { if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))) return $post_id; if(!current_user_can("edit_post", $post_id)) return $post_id; if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) return $post_id; $slug = "post"; if($slug != $post->post_type) return $post_id; $meta_box_text_value = ""; $meta_box_dropdown_value = ""; $meta_box_checkbox_value = ""; if(isset($_POST["meta-box-text"])) { $meta_box_text_value = $_POST["meta-box-text"]; } update_post_meta($post_id, "meta-box-text", $meta_box_text_value); if(isset($_POST["meta-box-dropdown"])) { $meta_box_dropdown_value = $_POST["meta-box-dropdown"]; } update_post_meta($post_id, "meta-box-dropdown", $meta_box_dropdown_value); if(isset($_POST["meta-box-checkbox"])) { $meta_box_checkbox_value = $_POST["meta-box-checkbox"]; } update_post_meta($post_id, "meta-box-checkbox", $meta_box_checkbox_value); } add_action("save_post", "save_custom_meta_box", 10, 3);

Here is how the code works: – save_post hook’s callback is triggered when a post, page and custom post type is saved. We attached a callback to save meta data. – We verify the nonce. If the nonce is not present or invalid then we don’t save the return the callback. – We check whether the current logged in admin user has permission to save meta data for that post type. If the user doesn’t have permission, then we return the callback. – We check if the post is being auto saved. If the save is auto saved, then we return the callback. – Final check is whether the post type is the same as the meta box post type. If not, then we return the callback. – We retrieve the values of the form fields using PHP $_POST variable and save them in database using update_post_meta. update_post_meta create a new meta data key/value in the database if the key is not present, otherwise it updates the key value.

代码的工作方式如下:– save_post帖子,页面和自定义帖子类型时,将触发save_post挂钩的回调。 我们附加了一个回调以保存元数据。 –我们验证随机数。 如果现时不存在或无效,那么我们不保存返回回调。 –我们检查当前登录的管理员用户是否有权保存该帖子类型的元数据。 如果用户没有权限,则我们返回回调。 –我们检查帖子是否被自动保存。 如果保存是自动保存的,那么我们返回回调。 –最后检查帖子类型是否与元框帖子类型相同。 如果不是,则返回回调。 –我们使用PHP $_POST变量检索表单字段的值,并使用update_post_meta将其保存在数据库中。 如果不存在密钥,则update_post_meta在数据库中创建一个新的元数据密钥/值,否则它将更新密钥值。

删除元框 (Removing a Meta Box)

We can remove custom meta boxes and the default WordPress core meta boxes using remove_meta_box. To remove a meta box you need its ID, screen and content.

我们可以使用remove_meta_box删除自定义的meta框和默认的WordPress核心meta框。 要删除元框,您需要其ID,屏幕和内容。

Here are the IDs of some important default meta boxes:

以下是一些重要的默认元框的ID:

‘authordiv’ – Author metabox

'authordiv'–作者metabox ‘categorydiv’ – Categories metabox

'categorydiv'–类别metabox ‘commentstatusdiv’ – Comments status metabox (discussion)

'commentstatusdiv'–评论状态元框(讨论) ‘commentsdiv’ – Comments metabox

'commentsdiv'–评论元框 ‘formatdiv’ – Formats metabox

'formatdiv'–格式元框 ‘pageparentdiv’ – Attributes metabox

'pageparentdiv'–属性元框 ‘postcustom’ – Custom fields metabox

'postcustom'–自定义字段元框 ‘postexcerpt’ – Excerpt metabox

'postexcerpt'–摘录元框 ‘postimagediv’ – Featured image metabox

'postimagediv'–特色图片metabox ‘revisionsdiv’ – Revisions metabox

'revisionsdiv'-版本元框 ‘slugdiv’ – Slug metabox

'slugdiv'– Slug metabox ‘submitdiv’ – Date, status, and update/save metabox

'submitdiv'-日期,状态和更新/保存元框 ‘tagsdiv-post_tag’ – Tags metabox

'tagsdiv-post_tag'–标签元框 ‘{$tax-name}div’ – Hierarchical custom taxonomies metabox

'{$ tax-name} div'–分层自定义分类法元框 ‘trackbacksdiv’ – Trackbacks metabox

'trackbacksdiv'–引用元框

Here is the code to remove custom fields meta box:

这是删除自定义字段元框的代码:

function remove_custom_field_meta_box() { remove_meta_box("postcustom", "post", "normal"); } add_action("do_meta_boxes", "remove_custom_field_meta_box");

Here we triggered remove_meta_box in do_meta_boxes hook. But you cannot always call remove_meta_box inside it. For example, to remove dashboard widgets you need to call it inside wp_dashboard_setup hook.

在这里,我们触发remove_meta_box在do_meta_boxes挂钩。 但是您不能总是在其中调用remove_meta_box 。 例如,要删除仪表板小部件,您需要在wp_dashboard_setup挂钩中调用它。

最后的想法 (Final Thoughts)

WordPress Meta Box APIs are very useful if you are building a plugin or theme. SEO, Post Series, and Related Content plugins make use of custom meta boxes to take additional user information for posts.

如果您要构建插件或主题,则WordPress Meta Box API非常有用。 SEO,帖子系列和相关内容插件利用自定义元框来获取帖子的其他用户信息。

翻译自: https://www.sitepoint.com/adding-custom-meta-boxes-to-wordpress/

相关资源:25个经典网站源代码
最新回复(0)