WordPress Add Add_meta_box Use method

Source: Internet
Author: User

Describe

The Add_meta_box () function was added to WordPress 2.5 to add meta modules to the admin interface to the plugin developer.

Usage

<?php
Add_meta_box ($id, $title, $callback, $post _type, $context, $priority, $callback _args);
?>
Parameters

$id

(string) (required) HTML "ID" attribute of the Meta module

$title

(string) (required) The title of the Meta module, visible to the user

$callback

(callback) (required) a function that outputs HTML code for a meta module

$post _type

(required) Displays the article type of the Meta module, which can be an article (post), a page, a link (link), an attachment (attachment), or a custom article type (custom article type alias)

$context

(optional) The display location of the Meta module (' Normal ', ' advanced ', or ' side ')

Default value: ' Advanced '

$priority

(optional) The priority level displayed by the Meta module (' High ', ' core ', ' Default ' or ' low ')

Defaults: ' Default '

$callback _args

(array) (optionally) the arguments passed to the callback function. The callback function will receive $post objects and any other arguments passed by this variable.

To add a custom field--"recommended index" for example, tell me how to use meta Box.

Note: The recommended index, in this case is the author of the article on the score, scores in 1~10 points, for integers. The higher the score, the more recommended.

Let's look at the final look, we can select the value by the Drop-down list.

First, you need to use the Add Meta boxes action, which allows us to register meta box for any article type, where we need to use the Add_meta_box () method to add information about meta box. The code is as follows

The code is as follows Copy Code

function Add_rating_meta_box ($post _type, $post) {


What post type is required add the recommended index Meta Box


$types = Array (' Post ', ' page ');





foreach ($types as $type) {


Add_meta_box (


The ID of ' rating_meta_box_id ',//meta box in the foreground page, can be obtained through JS to the Meta box


' Recommended index ',//display title


' Render_rating_meta_box ',//callback method, HTML code for output meta box


$type,//on which post Type page is added


' Side ',//Where to display the meta Box


' Default '//Priority


);


}


}


Add_action (' add_meta_boxes ', ' add_rating_meta_box ');


Here we define the custom field for both post and page in the $types array, and then tell WordPress to use the "Render_rating_meta_box" method to render the meta box, located in the sidebar (side). Because the content is not much, so the sidebar is enough, if more content, you can change "side" to "advanced", which will be in the main content area rendering meta Box.

Now let's see how it's rendered.

The code is as follows Copy Code


function Render_rating_meta_box ($post) {
Add a nonce entry for subsequent security checks
Wp_nonce_field (' rating_nonce_action ', ' rating_nonce_name ');

Get the value of the recommended index
$rating _key = ' rating ';
$rating _value = Get_post_meta ($post->id, $rating _key, True);
$rating _value = (int) $rating _value;

$html = ' <select name= ' Rating_field ' > ';
for ($i = 0; $i <= $i + +) {
$selected = ';
if ($i = = $rating _value) {
$selected = ' selected= ' selected ';
}
$html. = sprintf (' <option value= '%s '%s>%s star </option> ', $i, $selected, $i/2);
}
$html. = ' </select> ';
Echo $html;
}


Here you use Wp_nonce_field () to add a nonce field to do security checks, then read the value of the recommended index, loop 1~10 to output the values that are available, and select the default if the same as the recommended index. With the Drop-down box, you can solve the problem of inconvenient and unverifiable input. Remember the value of the Name property of the Drop-down box here (Rating_field), which will get the selected value in the following code.

Finally, when the article is saved, you need to save the recommended index.

The code is as follows Copy Code


function Save_rating_post_data ($post _id) {
Check to see if Nonce is set
if (!isset ($_post[' rating_nonce_name ')) {
return $post _id;
}
$nonce = $_post[' rating_nonce_name '];

Verify that the nonce is correct
if (!wp_verify_nonce ($nonce, ' rating_nonce_action ')) {
return $post _id;
}

If the system is automatically saved, it does not operate
if (defined (' Doing_autosave ') && doing_autosave) {
return $post _id;
}

Check User rights
if ($_post[' post_type '] = = ' POST ') {
if (!current_user_can (' Edit_post ', $post _id)) {
return $post _id;
}
}

$rating _key = ' rating ';
Get Data
$rating _value = $_post[' Rating_field '];

Update data
Update_post_meta ($post _id, $rating _key, $rating _value);
}
Add_action (' Save_post ', ' save_rating_post_data ');


Here is a series of checks, including the Nonce check just set up, the user permissions of the check, the exclusion of automatic preservation. The data is then stored in the database using the Update_post_meta () method.

At this point, we have completed the recommended index custom field modification, it is convenient to select the article recommended index.

Wait a minute...

Careful friends may find that, after the application of the above three pieces of code, can indeed implement the function. However, in the default custom column area, you can see that there is a column called "rating", which is the recommended index we just selected. If you want to let him not in the custom column, display, you can change the above code $rating_key to the following underlined, so that WordPress will not be displayed. Note that there are two places to change.

The code is as follows Copy Code


The original code
$rating _key = ' rating ';
The code after the change
$rating _key = ' _rating ';


add meta box to upload pictures


1. First to support the upload of pictures, to add code in the functions.php:

The code is as follows Copy Code
function my_add_edit_form_multipart_encoding () {
Echo ' enctype= ' multipart/form-data ';
}
Add_action (' Post_edit_form_tag ', ' my_add_edit_form_multipart_encoding ');

2. Then install meta box:

The code is as follows Copy Code
function My_setup_meta_boxes () {
Add_meta_box (' My_image_box ', ' Upload image ', ' my_render_image_attachment_box ', ' page ', ' normal ', ' high '); The parameters of this place you can go to the official website to view, I just want to explain the 4th parameter, if you want to post support to fill in the post if it is page to fill out the page, if it is a custom type to fill out the name of the custom type
}
Add_action (' Admin_init ', ' my_setup_meta_boxes ');

3. Add callback function:

The code is as follows Copy Code
function My_render_image_attachment_box ($post) {


Display the added picture


$existing _image_id = Get_post_meta ($post-&gt;id, ' _my_attached_image ', true);


if (Is_numeric ($existing _image_id)) {


Echo ' &lt;div&gt; ';


$arr _existing_image = wp_get_attachment_image_src ($existing _image_id, ' large ');


$existing _image_url = $arr _existing_image[0];


Echo ' &lt;img src= '. $existing _image_url. '/&gt; ';


Echo ' &lt;/div&gt; ';


}


If you've uploaded a picture, you're prompted.


if ($existing _image) {


Echo ' &lt;div&gt;attached Image ID: '. $existing _image. ' &lt;/div&gt; ';


}


Echo ' Upload an Image: &lt;input type= "file" Name= "My_image" id= "My_image";


Get the status of a picture


$status _message = Get_post_meta ($post-&gt;id, ' _my_attached_image_upload_feedback ', true);


Show Picture status


if ($status _message) {


Echo ' &lt;div class= ' upload_status_message ' &gt; ';


echo $status _message;


Echo ' &lt;/div&gt; ';


}


Automatically save


Echo ' &lt;input type= ' hidden ' name= ' My_manual_save_flag ' value= ' true '/&gt; ';


}

4. Picture update:

The code is as follows Copy Code
function My_update_post ($post _id, $post) {


Get Picture Type


$post _type = $post-&gt;post_type;


if ($post _id &amp;&amp; isset ($_post[' My_manual_save_flag ')) {


Switch ($post _type) {


Case ' page ':


if (Isset ($_files[' my_image ')) &amp;&amp; ($_files[' my_image '] [' size '] &gt; 0)) {


$arr _file_type = Wp_check_filetype (basename ($_files[' my_image '] [' name ']);


$uploaded _file_type = $arr _file_type[' type '];


$allowed _file_types = Array (' image/jpg ', ' image/jpeg ', ' image/gif ', ' image/png ');


if (In_array ($uploaded _file_type, $allowed _file_types)) {


$upload _overrides = Array (' Test_form ' =&gt; false);


$uploaded _file = wp_handle_upload ($_files[' my_image '), $upload _overrides);


if (isset ($uploaded _file[' file ')) {


$file _name_and_location = $uploaded _file[' file '];


$file _title_for_media_library = ' your title here ';


$attachment = Array (


' Post_mime_type ' =&gt; $uploaded _file_type,


' Post_title ' =&gt; ' uploaded image '. Addslashes ($file _title_for_media_library),


' Post_content ' =&gt; ',


' Post_status ' =&gt; ' inherit '


);


$attach _id = wp_insert_attachment ($attachment, $file _name_and_location);


Require_once (Abspath. "Wp-admin". '/includes/image.php ');


$attach _data = Wp_generate_attachment_metadata ($attach _id, $file _name_and_location);


Wp_update_attachment_metadata ($attach _id, $attach _data);


$existing _uploaded_image = (int) Get_post_meta ($post _id, ' _my_attached_image ', true);


if (Is_numeric ($existing _uploaded_image)) {


Wp_delete_attachment ($existing _uploaded_image);


}


Update_post_meta ($post _id, ' _my_attached_image ', $attach _id);


$upload _feedback = false;


} else {


$upload _feedback = ' There is a problem with your upload. '


Update_post_meta ($post _id, ' _my_attached_image ', $attach _id);


}


} else {


$upload _feedback = ' Please upload only image files (jpg, GIF or PNG). '


Update_post_meta ($post _id, ' _my_attached_image ', $attach _id);


}


} else {


$upload _feedback = false;


}


Update_post_meta ($post _id, ' _my_attached_image_upload_feedback ', $upload _feedback);


Break


Default


}


Return


}


Return


}


Add_action (' Save_post ', ' my_update_post ', 1,2);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.