search
HomeCMS TutorialWordPressHow 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' );

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;   
}

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; );

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;;

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
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How easy is it to manage content with WordPress?How easy is it to manage content with WordPress?May 09, 2025 am 12:11 AM

WordPressisuser-friendlyduetoitsintuitiveinterfaceandCMS,whichseparatescontentfromdesign.Itoffersarichtexteditorforeasycontentcreationandamedialibraryfororganization.Itsflexibilityisenhancedbynumerousthemesandplugins,thoughoverusecanimpactperformance

How is WordPress used in business settings?How is WordPress used in business settings?May 08, 2025 am 12:04 AM

WordPressissuitableforbusinesssettings.1)Itsupportse-commercewithpluginslikeWooCommerce,allowingproductmanagementandpaymentprocessing.2)ItservesasaCMSforcorporateblogs,enhancingSEOandengagement.3)Customizationispossiblewithnumerousthemesandplugins.4)

What types of websites are not a good fit for WordPress?What types of websites are not a good fit for WordPress?May 07, 2025 am 12:10 AM

WordPressisnotidealforhigh-trafficwebsites,customandcomplexapplications,security-sensitiveapplications,real-timedataprocessing,andhighlycustomizeduserinterfaces.Forhigh-trafficsites,useNext.jsorcustomsolutions;forcomplexapplications,optforDjangoorRub

Can you build a blog with WordPress?Can you build a blog with WordPress?May 06, 2025 am 12:03 AM

Yes,youcanbuildablogwithWordPress.1)ChoosebetweenWordPress.comforbeginnersorWordPress.orgformorecontrol.2)Selectathemetopersonalizeyourblog'slook.3)Usepluginstoenhancefunctionality,likeSEOandsocialmediaintegration.4)Customizeyourthemewithsimplecodetw

How secure is WordPress as a CMS platform?How secure is WordPress as a CMS platform?May 05, 2025 am 12:01 AM

WordPresscanbesecureifmanagedproperly.1)KeeptheWordPresscoreupdatedtopatchvulnerabilities.2)Vetandupdatepluginsandthemesfromreputablesources.3)Enforcestrongpasswordsandusetwo-factorauthentication.4)Chooseahostingproviderwithgoodsecuritypractices.5)Ed

What kind of websites can you build with WordPress CMS?What kind of websites can you build with WordPress CMS?May 04, 2025 am 12:06 AM

WordPresscanbuildvarioustypesofwebsites:1)Personalblogs,easytosetupwiththemesandplugins.2)Businesswebsites,usingdrag-and-dropbuilders.3)E-commerceplatforms,withWooCommerceforseamlessintegration.4)Communitysites,usingBuddyPressorbbPress.5)Educationalp

What are the pros and cons of using WordPress as your CMS?What are the pros and cons of using WordPress as your CMS?May 03, 2025 am 12:09 AM

WordPressisapowerfulCMSwithsignificantadvantagesandchallenges.1)It'suser-friendlyandcustomizable,idealforbeginners.2)Itsflexibilitycanleadtositebloatandsecurityissuesifnotmanagedproperly.3)Regularupdatesandperformanceoptimizationsarenecessarytomainta

How does WordPress compare to other popular CMS platforms?How does WordPress compare to other popular CMS platforms?May 02, 2025 am 12:18 AM

WordPressexcelsineaseofuseandadaptability,makingitidealforbeginnersandsmalltomedium-sizedbusinesses.1)EaseofUse:WordPressisuser-friendly.2)Security:Drupalleadswithstrongsecurityfeatures.3)Performance:GhostoffersexcellentperformanceduetoNode.js.4)Scal

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software