Create a simple CRM in WordPress: Create custom fields
In this series, we’ve been looking at how to create a simple CRM system in WordPress. In the first part of this series, we created a WordPress plugin that registers the “Contact” custom post type, but we haven’t covered how to store additional information for a contact.
Create custom fields
WordPress has the add_meta_box()
function that allows plugin and theme developers to register custom meta boxes for various WordPress admin screens.
WordPress registers some of its own meta boxes to display when you create a post or page. For example, on the page you have Page PropertiesMeta Box:
Let’s add a meta box to the Contact custom post type. Open the plug-in file you created in the first tutorial of this series. Then, in the plugin's constructor, update the code to match the following. This registers our register_meta_boxes()
function to add_meta_boxes
Action:
/** * Constructor. Called when plugin is initialised */ function __construct() { add_action( 'init', array( $this, 'register_custom_post_type' ) ); add_action( 'add_meta_boxes', array( $this, 'register_meta_boxes' ) ); }
Next, within our register_meta_boxes()
function, we add a call to add_meta_box()
. This tells WordPress that we need a meta box named Contact Details, which is rendered by the output_meta_box()
function. Add the following code after the constructor:
/** * Registers a Meta Box on our Contact Custom Post Type, called 'Contact Details' */ function register_meta_boxes() { add_meta_box( 'contact-details', 'Contact Details', array( $this, 'output_meta_box' ), 'contact', 'normal', 'high' ); }
Finally, we need a output_meta_box()
function, which is called by add_meta_box
above. Add the following code after the register_meta_boxes()
function:
/** * Output a Contact Details meta box * * @param WP_Post $post WordPress Post object */ function output_meta_box($post) { }
Let's check if a meta box appears on our Contact custom post type. Create a new contact in your WordPress dashboard by going to Contacts > Add New Contact
.If everything is written correctly, you should see something similar to the following screenshot:
Fill the meta box using fields
Let's go ahead and add an email address field to this meta box. Change the output_meta_box
function to the following code:
/** * Output a Contact Details meta box * * @param WP_Post $post WordPress Post object */ function output_meta_box( $post ) { // Output label and field echo ( '<label for="contact_email">' . __( 'Email Address', 'tuts-crm' ) . '</label>' ); echo ( '<input type="text" name="contact_email" id="contact_email" value="' . esc_attr( $email ) . '" />' ); }
Save your plugin code and reload the Add Contact screen. You should see our new email address field appear in the Contact Details meta box:
Save custom field data
We're not quite done yet. We need to tell WordPress to save what the user enters into the field. In WordPress we do this by registering a function for the save_post
action.
As with most operations, we will register our operation in the plugin's constructor:
/** * Constructor. Called when plugin is initialised */ function __construct() { add_action( 'init', array( $this, 'register_custom_post_type' ) ); add_action( 'add_meta_boxes', array( $this, 'register_meta_boxes' ) ); add_action( 'save_post', array( $this, 'save_meta_boxes' ) ); }
Next, let’s create the save_meta_boxes()
function:
/** * Saves the meta box field data * * @param int $post_id Post ID */ function save_meta_boxes( $post_id ) { // Check this is the Contact Custom Post Type if ( 'contact' != $_POST['post_type'] ) { return $post_id; } // Check the logged in user has permission to edit this post if ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; } // OK to save meta data $email = sanitize_text_field( $_POST['contact_email'] ); update_post_meta( $post_id, '_contact_email', $email ); }
This function performs multiple actions, as WordPress and other plugins can call the save_post
action very frequently (e.g. when automatically saving a draft on a regular basis or when saving a different post type). We need to ensure that the custom field data is only saved when the user saves or updates a contact.
If we were to save the contact, we would clean up the email address. From the WordPress Codex:
Checks for invalid UTF-8, converts single < characters to entities, strips all tags, removes newlines, tabs and extra spaces, strips octets. < 字符转换为实体,剥离所有标签,删除换行符、制表符和额外的空格,剥离八位字节。
In short, we ensure that there is no funky formatting in the text string.
Finally, we use update_post_meta
to store the email address in the post metadata. Think of a post meta as a sequence of key/value pairs attached to a post. You can choose as many as you like. In our example, we store the value of the custom field based on the key _contact_email
.
Read custom field data
Create a new Contact and enter an email address. Save the new contact and you will notice that the email address does not appear in the field:
We need to edit the output_meta_box()
function to read the Post meta and display it in the input field. Change the output_meta_box()
function to the following code:
/** * Output a Contact Details meta box * * @param WP_Post $post WordPress Post object */ function output_meta_box($post) { $email = get_post_meta( $post->ID, '_contact_email', true ); // Output label and field echo ( '<label for="contact_email">' . __( 'Email Address', 'tuts-crm' ) . '</label>' ); echo ( '<input type="text" name="contact_email" id="contact_email" value="' . esc_attr( $email ) . '" />' ); }
We use get_post_meta()
to get the value for a given post ID and meta key combination. We know the meta key is _contact_email
because that’s what we do in update_post_meta()
安全
提交和处理表单数据时,安全性极其重要。我们在保存数据时需要知道数据的来源是可信的。如果我们不能信任数据的来源,我们就不能存储它——数据可能会因试图利用错误或安全缺陷而受到损害或损坏。
WordPress 为我们提供了随机数(“使用一次的数字”),可以与表单数据一起发送。当我们的保存例程运行时,可以检查这个随机数,以确保它与我们期望的值匹配。
这有助于防止跨站点请求伪造 (CSRF) 攻击,即有人试图从不同的网站向我们的保存例程提交表单数据。
我们需要在上面的代码的两个地方添加安全性:
-
output_meta_box()
:向表单添加随机数 -
save_meta_boxes()
:验证提交的随机数值
让我们编辑 output_meta_box()
函数,将其替换为以下代码:
/** * Output a Contact Details meta box * * @param WP_Post $post WordPress Post object */ function output_meta_box($post) { $email = get_post_meta( $post->ID, '_contact_email', true ); // Add a nonce field so we can check for it later. wp_nonce_field( 'save_contact', 'contacts_nonce' ); // Output label and field echo ( '<label for="contact_email">' . __( 'Email Address', 'tuts-crm' ) . '</label>' ); echo ( '<input type="text" name="contact_email" id="contact_email" value="' . esc_attr( $email ) . '" />' ); }
这使用 wp_nonce_field()
生成一个名为 contacts_nonce
的隐藏字段,并执行名为 save_contact
的操作。它的价值是由WordPress产生的。
接下来,让我们在 save_meta_boxes()
中编辑保存例程:
/** * Saves the meta box field data * * @param int $post_id Post ID */ function save_meta_boxes( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['contacts_nonce'] ) ) { return $post_id; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['contacts_nonce'], 'save_contact' ) ) { return $post_id; } // Check this is the Contact Custom Post Type if ( 'contact' != $_POST['post_type'] ) { return $post_id; } // Check the logged in user has permission to edit this post if ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; } // OK to save meta data $email = sanitize_text_field( $_POST['contact_email'] ); update_post_meta( $post_id, '_contact_email', $email ); }
这为我们的保存例程添加了两项检查:
- 检查我们的表单中是否设置了随机数字段。如果没有,请不要保存任何内容。
- 检查随机数字段的值是否符合我们的预期。如果没有,请不要保存任何内容。
创建或编辑您的联系人,并确保电子邮件地址现已保存。
下一个...
在下一篇文章中,我们将使用高级自定义字段将自定义字段添加到我们的联系人自定义帖子类型中,从而使我们能够创建具有更广泛输入类型的丰富用户界面.
The above is the detailed content of Create a simple CRM in WordPress: Create custom fields. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

You can easily modify your WordPress page width by editing your style.css file: Edit your style.css file and add .site-content { max-width: [your preferred width]; }. Edit [your preferred width] to set the page width. Save changes and clear cache (optional).

WordPress posts are stored in the /wp-content/uploads folder. This folder uses subfolders to categorize different types of uploads, including articles organized by year, month, and article ID. Article files are stored in plain text format (.txt), and the filename usually includes its ID and title.

Create a product page in WordPress: 1. Create the product (name, description, pictures); 2. Customize the page template (add title, description, pictures, buttons); 3. Enter product information (stock, size, weight); 4 . Create variations (different colors, sizes); 5. Set visibility (public or hidden); 6. Enable/disable comments; 7. Preview and publish the page.

WordPress template files are located in the /wp-content/themes/[theme name]/ directory. They are used to determine the appearance and functionality of the website, including header (header.php), footer (footer.php), main template (index.php), single article (single.php), page (page.php), Archive (archive.php), category (category.php), tag (tag.php), search (search.php) and 404 error page (404.php). By editing and modifying these files, you can customize the appearance of your WordPress website

Search for authors in WordPress: 1. Once logged in to your admin panel, navigate to Posts or Pages, enter the author name using the search bar, and select Author in Filters. 2. Other tips: Use wildcards to broaden your search, use operators to combine criteria, or enter author IDs to search for articles.

The most stable WordPress version is the latest version because it contains the latest security patches, performance enhancements, and introduces new features and improvements. In order to update to the latest version, log into your WordPress dashboard, go to the Updates page and click Update Now.

WordPress is developed using PHP language as its core programming language for handling database interactions, form processing, dynamic content generation, and user requests. PHP was chosen for reasons including cross-platform compatibility, ease of learning, active community, and rich library and frameworks. Apart from PHP, WordPress also uses languages like HTML, CSS, JavaScript, SQL, etc. to enhance its functionality.
