Create a simple CRM in WordPress: Create custom fields

WBOY
Release: 2023-08-29 15:49:12
Original
1321 people have browsed it

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:

Create a simple CRM in WordPress: Create custom fields

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' ) ); 
    
}
Copy after login

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' );	
}
Copy after login

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

}
Copy after login

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:

Create a simple CRM in WordPress: Create custom fields

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 ) . '" />'  );
    
}
Copy after login

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:

Create a simple CRM in WordPress: Create custom fields

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' ) );
    
}
Copy after login

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 );
    
}
Copy after login

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:

Create a simple CRM in WordPress: Create custom fields

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 ) . '" />' );
    
}
Copy after login

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) 攻击,即有人试图从不同的网站向我们的保存例程提交表单数据。

我们需要在上面的代码的两个地方添加安全性:

  1. output_meta_box():向表单添加随机数
  2. 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 ) . '" />' );
    
}
Copy after login

这使用 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 );
    
}
Copy after login

这为我们的保存例程添加了两项检查:

  1. 检查我们的表单中是否设置了随机数字段。如果没有,请不要保存任何内容。
  2. 检查随机数字段的值是否符合我们的预期。如果没有,请不要保存任何内容。

创建或编辑您的联系人,并确保电子邮件地址现已保存。

下一个...

在下一篇文章中,我们将使用高级自定义字段将自定义字段添加到我们的联系人自定义帖子类型中,从而使我们能够创建具有更广泛输入类型的丰富用户界面.

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template