Home CMS Tutorial WordPress How to add Meta Box to WordPress

How to add Meta Box to WordPress

Jan 12, 2021 pm 04:59 PM
wordpress

The following tutorial column will introduce how to add Meta Box to WordPress , I hope it will be helpful to friends in need! The way to add Meta Box in WordPress requires the use of add meta boxes Action. This Action allows us to register Meta Box for any article type. In this Action, we need to use the add_meta_box() method to add Meta Box. Related Information. The code is as follows

function add_rating_meta_box($post_type, $post) {   
    // 需要哪些post type添加推荐指数 Meta Box   
    $types = array( 'post', 'page' );   

    foreach ( $types as $type ) {   
        add_meta_box(   
            'rating_meta_box_id', // Meta Box在前台页面中的id,可通过JS获取到该Meta Box   
            '推荐指数', // 显示的标题   
            'render_rating_meta_box', // 回调方法,用于输出Meta Box的HTML代码   
            $type, // 在哪个post type页面添加   
            'side', // 在哪显示该Meta Box   
            'default' // 优先级   
        );   
    }   
}   
add_action( 'add_meta_boxes', 'add_rating_meta_box' );
Copy after login

Here we define the custom field that both Post and Page need to recommend the index in the $types array, and then tell WordPress to use the "render_rating_meta_box" method to render the Meta Box, position In the sidebar. Because there is not much content, the sidebar is sufficient. If there is more content, you can change "side" to "advanced" so that the Meta Box will be rendered in the main content area.

Next let’s see how it is rendered

function render_rating_meta_box( $post ) {   
    // 添加 nonce 项用于后续的安全检查   
    wp_nonce_field( 'rating_nonce_action', 'rating_nonce_name' );   

    // 获取推荐指数的值   
    $rating_key = 'rating';   
    $rating_value = get_post_meta( $post->ID, $rating_key, true );   
    $rating_value = (int)$rating_value;   

    $html = &#39;<select name="rating_field">&#39;;   
    for ($i = 0; $i <= 10; $i++) {   
        $selected = &#39;&#39;;   
        if ($i == $rating_value) {   
            $selected = &#39;selected="selected"&#39;;   
        }   
        $html .= sprintf(&#39;<option value="%s" %s>%s星</option>&#39;, $i, $selected, $i/2);   
    }   
    $html .= &#39;</select>&#39;;   
    echo $html;   
}
Copy after login

Here we first use wp_nonce_field() to add a nonce field for security checking, then read the value of the recommended index and loop 1 ~10 to output optional values. If it is the same as the recommended index, it will be selected by default. Through the drop-down box, the problem of inconvenient input and inability to verify can be solved. Remember the value of the name attribute of the drop-down box here (rating_field), which will be used to obtain the selected value in the following code.

Finally, when the article is saved, the recommendation index needs to be saved as well

function save_rating_post_data( $post_id ) {   
    // 检查nonce是否设置   
    if (!isset($_POST[&#39;rating_nonce_name&#39;])) {   
        return $post_id;   
    }   
    $nonce = $_POST[&#39;rating_nonce_name&#39;];   

    // 验证nonce是否正确   
    if (!wp_verify_nonce( $nonce, &#39;rating_nonce_action&#39;)) {   
        return $post_id;   
    }   

    // 如果是系统自动保存,则不操作   
    if ( defined( &#39;DOING_AUTOSAVE&#39; ) && DOING_AUTOSAVE ) {   
        return $post_id;   
    }   

    // 检查用户权限   
    if ($_POST[&#39;post_type&#39;] == &#39;post&#39;) {   
        if (!current_user_can(&#39;edit_post&#39;, $post_id )) {   
            return $post_id;   
        }   
    }   

    $rating_key = &#39;rating&#39;;   
    // 获取数据   
    $rating_value = $_POST[&#39;rating_field&#39;];   

    // 更新数据   
    update_post_meta( $post_id, $rating_key, $rating_value );   
}   
add_action( &#39;save_post&#39;, &#39;save_rating_post_data&#39; );
Copy after login

A series of checks are done here, including the nonce check just set, user permissions check, and automatic exclusion Saved condition. Then use the update_post_meta() method to store the data in the database.

At this point, we have completed the modification of the custom field for the recommendation index, and we can easily select the recommendation index of the article.

etc. . .

Careful friends may have discovered that after applying the above three pieces of code, the function can indeed be realized. However, under the default custom column area, you can see that there is a column called "rating", which is the recommendation index we just selected. If you don’t want it to be displayed under the custom column, you can change $rating_key in the above code to start with an underscore, so that WordPress will not display it. Note that there are two places to change.

// 原来的代码   $rating_key = &#39;rating&#39;;   
// 改后的代码   $rating_key = &#39;_rating&#39;;
Copy after login

The above is the detailed content of How to add Meta Box to WordPress. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to write a header of a wordpress How to write a header of a wordpress Apr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

What to do if there is an error in wordpress What to do if there is an error in wordpress Apr 20, 2025 am 11:57 AM

WordPress Error Resolution Guide: 500 Internal Server Error: Disable the plug-in or check the server error log. 404 Page not found: Check permalink and make sure the page link is correct. White Screen of Death: Increase the server PHP memory limit. Database connection error: Check the database server status and WordPress configuration. Other tips: enable debug mode, check error logs, and seek support. Prevent errors: regularly update WordPress, install only necessary plugins, regularly back up your website, and optimize website performance.

How to import wordpress templates How to import wordpress templates Apr 20, 2025 am 10:18 AM

WordPress templates quickly create professional websites. The steps to import a template include: select and download the template. Log in to the WordPress dashboard. Select Theme from the Appearance menu. Click "Add New Theme". Click "Upload topic" and select the downloaded template .zip file. Click "Install Now". Click the "Activate" button. Customize the templates through the Customize menu.

See all articles