Table of Contents
Related PHP function analysis for writing custom storage fields in WordPress.
您可能感兴趣的文章:
Home Backend Development PHP Tutorial Analysis of related PHP functions for writing custom storage fields in WordPress, _PHP tutorial

Analysis of related PHP functions for writing custom storage fields in WordPress, _PHP tutorial

Jul 12, 2016 am 09:02 AM
wordpress Field

The custom fields of WordPress are the meta information (meta information) of the article. Using this function, the article can be expanded The function is essential knowledge for learning WordPress plug-in development and theme in-depth development, and it is convenient for storing some additional customized content for articles.

Custom fields are not only used by plug-in developers. Information about WordPress’s featured images, custom page templates and other functions are stored in the form of custom fields.

The "Custom Column" section in the article editor interface can manage fields except for fields whose names begin with "_" (if there is no "Custom Column" section, please turn it on in the "Display Options" in the upper right corner), so many WordPress itself The custom fields used cannot be managed here.
Storage Principle

Custom fields are very flexible. First, let’s talk about its storage principle and why it is so flexible. In the database, the wp_posts form that stores articles has only the default 20 items, which are used to store necessary article information.

20151225143034327.png (332×620)

The wp_postmeta table that stores custom fields has only four items, namely meta_id (the ID of the custom field), post_id (the ID of the article to which the custom field belongs), meta_key (the name of the custom field) and meta_value (the value of a custom field), generally we only need to pay attention to the two items meta_key and meta_value.

Because of this, each article can have custom fields with the same name but different values, and there can be unlimited custom fields. Any plug-ins and themes can use custom fields to expand article information.

The name of a custom field in an article can be repeated.

Add field

Custom fields can be operated on the article editing page, but this article mainly writes about development.

20151225143103462.png (832×428)

To add custom fields, you can use the add_post_meta() function:

add_post_meta( $post_id, $meta_key, $meta_value, $unique );
Copy after login

Parameters:

$post_id

(integer) (required) The ID of the post to which the custom field is added.

Default value: None

$meta_key

(String) (Required) The name of the custom field.

Default value: None

$meta_value

(Mixed) (Required) The value of the custom field.

Default value: None

$unique

(Boolean) (optional) If there is already a field with the same name, whether to add it repeatedly. True allows; False disallows.

Default value: False

Update field

To update the value of a field, you can use the update_post_meta() function:

update_post_meta( $post_id, $meta_key, $meta_value, $prev_value );
Copy after login

Parameters:

$post_id

(integer) (required) The ID of the article to update the custom field.

Default value: None

$meta_key

(String) (Required) The name of the custom field to update.

Default value: None

$meta_value

(Mixed) (Required) The value of the custom field to update.

Default value: None

$prev_value

(Mixed) (Optional) This parameter is only useful if a post has multiple custom fields with the same name. If left blank, all fields with the same name are updated, otherwise fields with the same value as this parameter are updated.

Default value: empty string

Get field

To obtain fields, you can use the get_post_meta() function:

get_post_meta( $post_id, $key, $single );
Copy after login

Parameters:

$post_id

(integer) (required) The article ID of the field to be obtained, if in a loop, can be set using get_the_ID().

Default value: None

$key

(String) (optional) The name of the field to get.

Default value: None

$single

(Boolean) (optional) If True, returns a string; if False, returns an array, and the values ​​of custom fields with the same key value will be combined into a sequence array in the order of addition.

Default value: False

Example

The following is a simple example of browsing statistics:

function Bing_statistics_visitors( $cache = false ){
  if( !is_singular() ) return;
  global $post;
  $id = $post->ID;
  if( get_post( $id )->post_status != 'publish' ) return;
  $post_views = (int) get_post_meta( $id, 'views', true );
  update_post_meta( $id, 'views', ( $post_views + 1 ) ) || add_post_meta( $id, 'views', 1, true );
}
add_action( 'wp_head', 'Bing_statistics_visitors' );
Copy after login
Get the count:
function Bing_get_views(){
  global $post;
  $views = number_format( (int) get_post_meta( $post->ID, 'views', true ) );
  return $views;
}

Copy after login

Invisible custom fields
Although there are many custom fields created by WordPress in the database, they are not displayed in the "Custom Column" of the article editor (there is no "Custom Column" section, please click the "Display Options" in the upper right corner enabled), such as whether featured images, custom page templates, and comments are enabled, etc.

If you observe carefully, you will find that the names of these custom fields all start with an underscore "_". Therefore, the custom fields starting with an underscore "_" will not be displayed to the user, and the_meta() function will not be displayed to the user. It is not output and is hidden from the user.

20151225143222855.png (827×410)

利用这个特性,我们可以把不想让用户随便修改的字段、会让用户感到困惑的字段,比如已经提供设置界面的设置选项、缓存数据等等,以免出现错误。

下边是一个小例子:

add_post_meta( get_the_ID(), '_time_diff', time() );
Copy after login

另外,如果自定义字段储存的内容是数组即使名字前边不是下划线 “_” 也不会显示。

您可能感兴趣的文章:

  • WordPress判断用户是否登录的代码
  • 详解WordPress中提醒安装插件以及隐藏插件的功能实现
  • 给WordPress的编辑后台添加提示框的代码实例分享
  • 详解WordPress开发中过滤属性以及Sql语句的函数使用
  • WordPress中创建用户角色的相关PHP函数使用详解

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1084529.htmlTechArticleWordPress中编写自定义存储字段的相关PHP函数解析, WordPress 的自定义字段就是文章的 meta 信息(元信息),利用这个功能,可以扩展文章的...
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 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 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 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 >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.

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.

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 display wordpress comments How to display wordpress comments Apr 20, 2025 pm 12:06 PM

Enable comments in WordPress website: 1. Log in to the admin panel, go to "Settings" - "Discussions", and check "Allow comments"; 2. Select a location to display comments; 3. Customize comments; 4. Manage comments, approve, reject or delete; 5. Use <?php comments_template(); ?> tags to display comments; 6. Enable nested comments; 7. Adjust comment shape; 8. Use plugins and verification codes to prevent spam comments; 9. Encourage users to use Gravatar avatar; 10. Create comments to refer to

See all articles