我有一个插件设置页面,用户可以在其中打开或关闭自定义帖子类型。当插件初始化时,我会检查这个设置,看看是否应该注册自定义内容类型。这个registerPostType()
方法调用init
措施:
class CPT {
private $enabled = false;
public function __construct()
{
// Handle form submission.
add_action(\'init\', array($this, \'checkFormSubmission\'), 8);
// Load settings.
$settings = get_option(\'cpt_settings\');
$this->enabled = $settings[\'enabled\'];
// Add menu.
add_action(\'admin_menu\', array($this, \'registerMenu\'));
// Register custom post type if enabled.
if ($this->enabled) {
add_action(\'init\', array($this, \'registerPostType\'));
}
}
public function registerMenu()
{
add_submenu_page(
\'options-general.php\',
__(\'CPT Settings\', \'cpt\'),
__(\'CPT Settings\', \'cpt\'),
\'manage_options\',
\'cpt\',
array($this, \'renderSettingsPage\')
);
}
public function registerPostType()
{
$args = array(
\'labels\' => array(
\'name\' => \'CPT\',
),
\'public\' => true,
\'publicly_queryable\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'query_var\' => true,
\'capability_type\' => \'post\',
\'has_archive\' => true,
\'hierarchical\' => false,
\'menu_position\' => null,
\'supports\' => array(\'title\', \'editor\', \'author\', \'thumbnail\', \'excerpt\')
);
register_post_type(\'sample-cpt\', $args);
}
public function checkFormSubmission()
{
// Validate so user has correct privileges.
if (!current_user_can(\'manage_options\')) {
die(__(\'You are not allowed to perform this action.\', \'cpt\'));
}
// Check if settings form is submitted.
if (filter_input(INPUT_POST, \'cpt-settings\', FILTER_SANITIZE_STRING)) {
// Verify nonce and referer.
check_admin_referer(\'cpt-settings-action\', \'cpt-settings-nonce\');
$this->enabled = filter_input(
INPUT_POST,
\'cpt-enable\',
FILTER_VALIDATE_BOOLEAN
);
update_option(\'cpt_settings\', array(\'enabled\' => $this->enabled));
}
}
public function renderSettingsPage()
{
require_once plugin_dir_path(__FILE__ ) . \'/admin/templates/settings-page.php\';
}
}
new CPT();
这与预期的一样,但问题是,当我保存表单时,自定义帖子类型的菜单项在我重新加载页面之前不会更新。显然,这是因为菜单已经创建。
我的第一个想法是,我没有使用正确的挂钩来处理表单提交和注册我的自定义帖子,或者应该以更高的优先级添加挂钩?
我试着用wp_redirect()
保存设置后,我无法设置任何标题,因为输出已经开始。
有人能解释一下,在保存插件设置时,我如何更新自定义帖子类型的菜单项吗?