Table of Contents
Custom function
Register custom functionality on our custom post types
Create a new WordPress user role and assign it new custom capabilities
Create/edit WordPress users and assign them to new contact roles
为其他角色分配自定义功能
清洁提升我们的角色
摘要
Home Backend Development PHP Tutorial Building a basic CRM in WordPress: Leveraging custom features

Building a basic CRM in WordPress: Leveraging custom features

Aug 29, 2023 pm 08:01 PM

We have been looking at how to create a simple CRM system in WordPress. In the final part of this series, we looked at how to use roles to restrict user access to parts of the WordPress admin interface.

Today we’ll cover how to use custom features to restrict access only to a contact’s custom post type.

Custom function

While we previously reduced access levels for WordPress users, users can still manage posts and comments by assigning them to the Editor or Author role. None of these features are useful to us, so we need to further restrict access by allowing specified users to only access the Contact custom post type.

We can do this in the following ways:

  1. Register custom functionality on our custom post types
  2. Create a new WordPress user role and assign only our new custom features to that role
  3. Create/edit WordPress users and assign them to new contact roles

Register custom functionality on our custom post types

Registering custom features allows us to later define which WordPress roles have access to those features, for example, whether authors can create new contacts.

Let's edit the register_post_type() function call of the plugin file, replacing capability_type => 'post' with the following:

'capabilities' => array(
    'edit_others_posts'		=> 'edit_others_contacts',
	'delete_others_posts'	=> 'delete_others_contacts',
	'delete_private_posts'	=> 'delete_private_contacts',
	'edit_private_posts'	=> 'edit_private_contacts',
	'read_private_posts'	=> 'read_private_contacts',
	'edit_published_posts'	=> 'edit_published_contacts',
	'publish_posts'			=> 'publish_contacts',
	'delete_published_posts'=> 'delete_published_contacts',
	'edit_posts'			=> 'edit_contacts'	,
	'delete_posts'			=> 'delete_contacts',
	'edit_post' 			=> 'edit_contact',
    'read_post' 			=> 'read_contact',
    'delete_post' 			=> 'delete_contact',
),
'map_meta_cap' => true,
Copy after login

Our register_post_type() function should now look like this:

/**
* Registers a Custom Post Type called contact
*/
function register_custom_post_type() {
	register_post_type( 'contact', array(
        'labels' => array(
			'name'               => _x( 'Contacts', 'post type general name', 'tuts-crm' ),
			'singular_name'      => _x( 'Contact', 'post type singular name', 'tuts-crm' ),
			'menu_name'          => _x( 'Contacts', 'admin menu', 'tuts-crm' ),
			'name_admin_bar'     => _x( 'Contact', 'add new on admin bar', 'tuts-crm' ),
			'add_new'            => _x( 'Add New', 'contact', 'tuts-crm' ),
			'add_new_item'       => __( 'Add New Contact', 'tuts-crm' ),
			'new_item'           => __( 'New Contact', 'tuts-crm' ),
			'edit_item'          => __( 'Edit Contact', 'tuts-crm' ),
			'view_item'          => __( 'View Contact', 'tuts-crm' ),
			'all_items'          => __( 'All Contacts', 'tuts-crm' ),
			'search_items'       => __( 'Search Contacts', 'tuts-crm' ),
			'parent_item_colon'  => __( 'Parent Contacts:', 'tuts-crm' ),
			'not_found'          => __( 'No contacts found.', 'tuts-crm' ),
			'not_found_in_trash' => __( 'No contacts found in Trash.', 'tuts-crm' ),
		),
        
        // Frontend
        'has_archive' => false,
        'public' => false,
        'publicly_queryable' => false,
        
        // Admin
        'capabilities' => array(
	        'edit_others_posts'		=> 'edit_others_contacts',
			'delete_others_posts'	=> 'delete_others_contacts',
			'delete_private_posts'	=> 'delete_private_contacts',
			'edit_private_posts'	=> 'edit_private_contacts',
			'read_private_posts'	=> 'read_private_contacts',
			'edit_published_posts'	=> 'edit_published_contacts',
			'publish_posts'			=> 'publish_contacts',
			'delete_published_posts'=> 'delete_published_contacts',
			'edit_posts'			=> 'edit_contacts'	,
			'delete_posts'			=> 'delete_contacts',
			'edit_post' 			=> 'edit_contact',
	        'read_post' 			=> 'read_contact',
	        'delete_post' 			=> 'delete_contact',
        ),
        'map_meta_cap' => true,
        'menu_icon' => 'dashicons-businessman',
        'menu_position' => 10,
        'query_var' => true,
        'show_in_menu' => true,
        'show_ui' => true,
        'supports' => array(
        	'title',
        	'author',
        	'comments',
        ),
    ) );	
}
Copy after login

Two things happen here:

  1. We define our own capabilities using capability parameters and map them to their Post equivalents. This ensures that WordPress understands exactly what these functions mean (i.e. edit_contact behaves the same way as edit_post except that it works with our Contact custom post type).
  2. We have told WordPress to use map_meta_cap to map the above functionality to WordPress's raw functionality for enforcement purposes.

Reload WordPress admin as any user and you will see that our Contact custom post type has disappeared from the WordPress admin menu:

在 WordPress 中构建基本 CRM:利用自定义功能

This happens because we now need to tell WordPress which roles have the new contacts functionality (edit_contact, edit_contacts, etc.).

Create a new WordPress user role and assign it new custom capabilities

Using add_role(), we can create a new WordPress user role and assign our contact functionality to it. The role is stored in the WordPress options data, so we only have to call the function once.

To do this, add the following function at the end of the __construct() function in our plugin:

/**
* Activation hook to register a new Role and assign it our Contact Capabilities
*/
function plugin_activation() {
	
	// Define our custom capabilities
	$customCaps = array(
		'edit_others_contacts'			=> true,
		'delete_others_contacts'		=> true,
		'delete_private_contacts'		=> true,
		'edit_private_contacts'			=> true,
		'read_private_contacts'			=> true,
		'edit_published_contacts'		=> true,
		'publish_contacts'			=> true,
		'delete_published_contacts'		=> true,
		'edit_contacts'				=> true,
		'delete_contacts'			=> true,
		'edit_contact'				=> true,
		'read_contact'				=> true,
		'delete_contact'			=> true,
		'read'					=> true,
	);
	
	// Create our CRM role and assign the custom capabilities to it
	add_role( 'crm', __( 'CRM', 'tuts-crm'), $customCaps );
	
}
Copy after login

This feature will add a new role called CRM to WordPress. Users assigned to this role can only access the Contacts feature. Therefore, they can only access the Contact custom post type.

Please note that we also assigned the read capability to this role. This is required to allow users to edit their profile (name, password, etc.). We need to allow users to do this because when they log in, WordPress automatically redirects them to the profile screen.

If we did not assign the read function, the following would happen when the user logs in:

在 WordPress 中构建基本 CRM:利用自定义功能

To run our plugin_activation() function once, we add the following code to the end of the plugin file:

register_activation_hook( __FILE__, array( &$wpTutsCRM, 'plugin_activation' ) );
Copy after login

This tells WordPress that when activating the plugin, it needs to call the plugin_activation() function in the WPTutsCRM class.

Create/edit WordPress users and assign them to new contact roles

Next, deactivate and reactivate your plugin, then navigate to Users > Add New in the WordPress admin interface.

If all goes well, you will see the new CRM role appear in the drop-down list:

在 WordPress 中构建基本 CRM:利用自定义功能

Let’s go ahead and create a new user named crm and log in as that new user. We should now see our Contacts, with Dashboard and Profile being the only other menu options:

在 WordPress 中构建基本 CRM:利用自定义功能

为其他角色分配自定义功能

如果我们注销并以 WordPress 管理员、编辑或作者身份重新登录,您会发现 WordPress 管理菜单中仍然缺少联系人自定义帖子类型:

在 WordPress 中构建基本 CRM:利用自定义功能

这个是因为我们只分配了 CRM 角色我们的联系人自定义帖子类型的功能。因此,所有其他用户角色仍然无权访问此帖子类型。

To fix this, let’s assign the Custom Capabilities to the Administrator and Editor Roles by adding the following code to the end of the plugin_activation() function:

// Add custom capabilities to Admin and Editor Roles
$roles = array( 'administrator', 'editor' );
foreach ( $roles as $roleName ) {
	// Get role
	$role = get_role( $roleName );
	
	// Check role exists
	if ( is_null( $role) ) {
		continue;
	}
	
	// Iterate through our custom capabilities, adding them
	// to this role if they are enabled
	foreach ( $customCaps as $capability => $enabled ) {
		if ( $enabled ) {
			// Add capability
			$role->add_cap( $capability );
		}
	}
}
Copy after login

在这里,我们迭代要为其分配自定义功能的角色,检查该角色是否存在。如果是,我们就会迭代之前定义的自定义功能,将它们添加到角色中。

您会注意到我们没有向作者角色添加任何自定义功能;这是因为我们不想分配所有功能,因为作者角色传统上只允许对该用户自己的帖子进行写入访问。

让我们通过为作者角色添加一些功能来继续构建我们的 plugin_activation() 函数:

// Add some of our custom capabilities to the Author Role
$role = get_role( 'author' );
$role->add_cap( 'edit_contact' );
$role->add_cap( 'edit_contacts' );
$role->add_cap( 'publish_contacts' );
$role->add_cap( 'read_contact' );
$role->add_cap( 'delete_contact' );
unset( $role );
Copy after login

我们的整个函数现在应该如下所示:

/**
* Activation hook to register a new Role and assign it our Contact Capabilities
*/
function plugin_activation() {
	
	// Define our custom capabilities
	$customCaps = array(
		'edit_others_contacts'			=> true,
		'delete_others_contacts'		=> true,
		'delete_private_contacts'		=> true,
		'edit_private_contacts'			=> true,
		'read_private_contacts'			=> true,
		'edit_published_contacts'		=> true,
		'publish_contacts'				=> true,
		'delete_published_contacts'		=> true,
		'edit_contacts'					=> true,
		'delete_contacts'				=> true,
		'edit_contact'					=> true,
		'read_contact'					=> true,
		'delete_contact'				=> true,
		'read'							=> true,
	);
	
	// Create our CRM role and assign the custom capabilities to it
	add_role( 'crm', __( 'CRM', 'tuts-crm'), $customCaps );
	
	// Add custom capabilities to Admin and Editor Roles
	$roles = array( 'administrator', 'editor' );
	foreach ( $roles as $roleName ) {
		// Get role
		$role = get_role( $roleName );
		
		// Check role exists
		if ( is_null( $role) ) {
			continue;
		}
		
		// Iterate through our custom capabilities, adding them
		// to this role if they are enabled
		foreach ( $customCaps as $capability => $enabled ) {
			if ( $enabled ) {
				// Add capability
				$role->add_cap( $capability );
			}
		}
	}
			
	// Add some of our custom capabilities to the Author Role
	$role = get_role( 'author' );
	$role->add_cap( 'edit_contact' );
	$role->add_cap( 'edit_contacts' );
	$role->add_cap( 'publish_contacts' );
	$role->add_cap( 'read_contact' );
	$role->add_cap( 'delete_contact' );
	unset( $role );
	
}
Copy after login

以管理员、编辑或作者身份登录现在将在 WordPress 管理菜单中显示“联系人”选项:

在 WordPress 中构建基本 CRM:利用自定义功能

清洁提升我们的角色

如果 WordPress 管理员停用我们的插件,CRM 角色将保留在 WordPress 中。但是,鉴于没有其他插件或 WordPress 的一部分使用此角色,因此它是多余的 - 因此我们需要确保在停用我们的插件时删除 CRM 角色。

为此,请在 plugin_activation() 函数下方添加以下函数:

/**
* Deactivation hook to unregister our existing Contacts Role
*/
function plugin_deactivation() {
	
	remove_role( 'crm' );
	
}
Copy after login

与我们在插件激活时使用 register_activation_hook() 函数的方式相同,当我们的插件停用时,我们可以使用 register_deactivation_hook() 函数。让我们在 register_activation_hook 调用下面添加以下内容:

register_deactivation_hook( __FILE__, array( &$wpTutsCRM, 'plugin_deactivation' ) );
Copy after login

停用我们的插件后,我们的 CRM 角色将不再可用。

摘要

我们已经在 WordPress 中成功创建了一个简单的 CRM 系统,探索使用自定义帖子类型、帖子元字段和第三方插件集成来存储有关我们的客户和潜在客户的信息。

本教程还涵盖了 WordPress 的一些更高级的方面,包括通过 WP_List_Table 列显示高级自定义字段数据、过滤我们的帖子查询以搜索我们的高级自定义字段数据,以及通过角色和功能管理用户访问以限制访问仅限我们的 CRM 系统。

The above is the detailed content of Building a basic CRM in WordPress: Leveraging custom features. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles