search
HomeCMS TutorialWordPressA brief analysis of how to add a custom field panel in WordPress

How to add a custom field panel in WordPress? The following article will introduce to you how to add a custom field panel in WordPress. I hope it will be helpful to you!

A brief analysis of how to add a custom field panel in WordPress

## When we write articles in WordPress, we often use some custom fields, such as the two meta tags of web page description and keywords. Regarding these two For a tag, you can read an article I wrote before:

WordPress sets independent Description and Keywords

Usually when adding custom fields and their values, we do it manually It seems a bit troublesome to select the corresponding field in the drop-down box of the "Custom Field" module, then enter its value, and finally submit and wait for a short period of time. So is it possible to create a separate panel for these commonly used custom fields and just fill in the content directly? Just like article tags, you can add tags directly without submitting them separately. The answer is yes, here is the rendering:

A brief analysis of how to add a custom field panel in WordPress

I will teach you how to operate it below. Place all the following codes into functions.php of the current theme.

1. Create the required field information

Here we will add two custom fields, named _description_value and _keywords_value respectively. You can give The following array adds multiple elements to achieve the purpose of adding multiple custom fields.

The first element of the array, name, is the name of the custom field. In this code, the name of the custom field is the name value plus _value to prevent conflicts with other codes, such as _description_value; std is self Define the default value of the field. When you publish an article and no value is filled in the custom field, the default value will be used; title is the title of the custom field module, such as "Abstract", "Category" and "Tag" on the article editing page ", these are module names.

$new_meta_boxes =array(
  "description" => array(
    "name" => "_description",
    "std" => "这里填默认的网页描述",
    "title" => "网页描述:"),

  "keywords" => array(
    "name" => "_keywords",
    "std" => "这里填默认的网页关键字",
    "title" => "关键字:"));

2. Create a custom field input box

The following code will be used to create a custom field and input box, just copy it

function new_meta_boxes() {
  global $post, $new_meta_boxes;

  foreach($new_meta_boxes as $meta_box) {
    $meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);

    if($meta_box_value == "")
      $meta_box_value = $meta_box['std'];

    // 自定义字段标题
    echo&#39;<h3 id="meta-box-title">&#39;.$meta_box[&#39;title&#39;].&#39;</h3>&#39;;

    // 自定义字段输入框
    echo &#39;<textarea cols="60" rows="3" name="&#39;.$meta_box[&#39;name&#39;].&#39;_value">&#39;.$meta_box_value.&#39;</textarea><br />&#39;;
  }
   
  echo &#39;<input type="hidden" name="ludou_metaboxes_nonce" id="ludou_metaboxes_nonce" value="&#39;.wp_create_nonce( plugin_basename(__FILE__) ).&#39;" />&#39;;}

3. Create a custom field module

The following code will add a custom field module to the article editing page, which uses WordPress’s add module function

add_meta_box. This is exactly the opposite of what was done in the previous article WordPress article editing page to delete related modules.

function create_meta_box() {
  if ( function_exists(&#39;add_meta_box&#39;) ) {
    add_meta_box( &#39;new-meta-boxes&#39;, &#39;自定义模块&#39;, &#39;new_meta_boxes&#39;, &#39;post&#39;, &#39;normal&#39;, &#39;high&#39; );
  }}

4. Save article data

All preparations have been made before, the most important thing is to save the data in our custom fields information.

function save_postdata( $post_id ) {
  global $new_meta_boxes;
   
  if ( !wp_verify_nonce( $_POST[&#39;ludou_metaboxes_nonce&#39;], plugin_basename(__FILE__) ))
    return;
   
  if ( !current_user_can( &#39;edit_posts&#39;, $post_id ))
    return;
               
  foreach($new_meta_boxes as $meta_box) {
    $data = $_POST[$meta_box[&#39;name&#39;].&#39;_value&#39;];

    if($data == "")
      delete_post_meta($post_id, $meta_box[&#39;name&#39;].&#39;_value&#39;, get_post_meta($post_id, $meta_box[&#39;name&#39;].&#39;_value&#39;, true));
    else
      update_post_meta($post_id, $meta_box[&#39;name&#39;].&#39;_value&#39;, $data);
   }}

5. Connect the function to the specified action

This is the last step and the most important step, we have to do The purpose is to connect the function to the specified action (action) to let the WordPress program execute the function we wrote before:

add_action(&#39;admin_menu&#39;, &#39;create_meta_box&#39;);
add_action(&#39;save_post&#39;, &#39;save_postdata&#39;);
Okay, that’s all we have to do, now you can To call these two custom fields in your theme, use a text editor to open header.php in the theme directory, and copy the following code to to customize the description and keywords for your web page. Tags, please use the search engine for more specific operations:

<?phpif (is_single()) {
  // 自定义字段名称为 description_value
  $description = get_post_meta($post->ID, "_description_value", true);

  // 自定义字段名称为 keywords_value
  $keywords = get_post_meta($post->ID, "_keywords_value", true);

  // 去除不必要的空格和HTML标签
  $description = trim(strip_tags($description));
  $keywords = trim(strip_tags($keywords));

  echo &#39;<meta name="description" content="&#39;.$description.&#39;" />
<meta name="keywords" content="&#39;.$keywords.&#39;" />&#39;;
}
?>

Recommended learning: "

WordPress Tutorial"

The above is the detailed content of A brief analysis of how to add a custom field panel in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:露兜即刻. If there is any infringement, please contact admin@php.cn delete
Can you use WordPress to build a membership site?Can you use WordPress to build a membership site?May 01, 2025 am 12:08 AM

Yes,youcanuseWordPresstobuildamembershipsite.Here'show:1)UsepluginslikeMemberPress,PaidMemberSubscriptions,orWooCommerceforusermanagement,contentaccesscontrol,andpaymenthandling.2)Ensurecontentprotectionwithupdatedpluginsandadditionalsecuritymeasures

Does WordPress require coding knowledge to use as a CMS?Does WordPress require coding knowledge to use as a CMS?Apr 30, 2025 am 12:03 AM

You don't need programming knowledge to use WordPress, but mastering programming can improve the experience. 1) Use CSS and HTML to adjust the theme style. 2) PHP knowledge can edit topic files and add functions. 3) Custom plug-ins and meta tags can optimize SEO. 4) Pay attention to backup and use of sub-topics to prevent update issues.

What are the security considerations when using WordPress?What are the security considerations when using WordPress?Apr 29, 2025 am 12:01 AM

TosecureaWordPresssite,followthesesteps:1)RegularlyupdateWordPresscore,themes,andpluginstopatchvulnerabilities.2)Usestrong,uniquepasswordsandenabletwo-factorauthentication.3)OptformanagedWordPresshostingorsecuresharedhostingwithawebapplicationfirewal

How does WordPress compare to other website builders?How does WordPress compare to other website builders?Apr 28, 2025 am 12:04 AM

WordPressexcelsoverotherwebsitebuildersduetoitsflexibility,scalability,andopen-sourcenature.1)It'saversatileCMSwithextensivecustomizationoptionsviathemesandplugins.2)Itslearningcurveissteeperbutofferspowerfulcontroloncemastered.3)Performancecanbeopti

5  WordPress Plugins for Developers To Use in 20255 WordPress Plugins for Developers To Use in 2025Apr 27, 2025 am 08:25 AM

Seven Must-Have WordPress Plugins for 2025 Website Development Building a top-tier WordPress website in 2025 demands speed, responsiveness, and scalability. Achieving this efficiently often hinges on strategic plugin selection. This article highlig

What would you use WordPress for?What would you use WordPress for?Apr 27, 2025 am 12:14 AM

WordPresscanbeusedforvariouspurposesbeyondblogging.1)E-commerce:WithWooCommerce,itcanbecomeafullonlinestore.2)Membershipsites:PluginslikeMemberPressenableexclusivecontentareas.3)Portfoliosites:ThemeslikeAstraallowstunninglayouts.Ensuretomanageplugins

Is WordPress good for creating a portfolio website?Is WordPress good for creating a portfolio website?Apr 26, 2025 am 12:05 AM

Yes,WordPressisexcellentforcreatingaportfoliowebsite.1)Itoffersnumerousportfolio-specificthemeslike'Astra'foreasycustomization.2)Pluginssuchas'Elementor'enableintuitivedesign,thoughtoomanycanslowthesite.3)SEOisenhancedwithtoolslike'YoastSEO',boosting

What are the advantages of using WordPress over coding a website from scratch?What are the advantages of using WordPress over coding a website from scratch?Apr 25, 2025 am 12:16 AM

WordPressisadvantageousovercodingawebsitefromscratchdueto:1)easeofuseandfasterdevelopment,2)flexibilityandscalability,3)strongcommunitysupport,4)built-inSEOandmarketingtools,5)cost-effectiveness,and6)regularsecurityupdates.Thesefeaturesallowforquicke

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

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool