主题开发文档

💡 云策文档标注

概述

本文档介绍 WordPress Customizer API 的高级主题,包括如何扩展 Customizer 的访问权限,使其超越主题定制范围,适用于更广泛的用户角色。

关键要点

  • Customizer API 正在积极开发中,高级主题可通过 Slack 的 #core-customize 频道档案搜索获取更多讨论。
  • Customizer 访问权限由 customize 元能力控制,默认映射到 edit_theme_options,仅管理员拥有;可通过调整权限允许非管理员用户访问。
  • 允许非管理员访问 Customizer 可扩展其应用场景,例如用于定制文章,这是扩大 Customizer 使用范围的重要步骤。

代码示例

function allow_users_who_can_edit_posts_to_customize( $caps, $cap, $user_id ) {
	$required_cap = 'edit_posts';
	if ( 'customize' === $cap && user_can( $user_id, $required_cap ) ) {
		$caps = array( $required_cap );
	}
	return $caps;
}
add_filter( 'map_meta_cap', 'allow_users_who_can_edit_posts_to_customize', 10, 3 );

注意事项

如果为非管理员用户授予 customize 元能力,目前需要手动在管理菜单、管理栏或其他位置添加 Customizer 链接。


📄 原文内容

The customize API is actively developed; this page contains additional more advanced topics. Additional discussion of advanced topics cab be found by searching the archives for the #core-customize channel in Slack.

Allow Non-administrators to Access the Customizer

Customizer access is controlled by the customize meta capability (mapped to edit_theme_options by default), which is assigned only to administrators by default. This allows for wider use of the Customizer’s extensive capability-access options, which are built into panels, sections, and settings. Additionally, this makes it possible to allow non-administrators to use the customizer for, for example, customizing posts. This change is an important step toward expanding the scope of the Customizer beyond themes.

<?php
function allow_users_who_can_edit_posts_to_customize( $caps, $cap, $user_id ) {
	$required_cap = 'edit_posts';
	if ( 'customize' === $cap && user_can( $user_id, $required_cap ) ) {
		$caps = array( $required_cap );
	}
	return $caps;
}
add_filter( 'map_meta_cap', 'allow_users_who_can_edit_posts_to_customize', 10, 3 );

Note that it is currently necessary to manually add links to the Customizer in the admin menu, admin bar, or elsewhere if you are granting the customize meta capability to non-administrator users.