カスタム投稿タイプに独自の権限を与えてみた

カスタム投稿タイプに独自の権限を与えてみた

少し特殊な利用方法となりますが、カスタム投稿タイプで追加した項目の追加・編集・削除権限を持つ独自の権限グループを作る方法について、残しておきます。

実装内容

カスタム投稿タイプの追加については「register_post_type」、権限グループの追加については「add_role」、また、そのグループに対して独自のルールを持たせるのが「add_cap」となります。

最終的に以下の内容をfunctions.phpに入力することで、「ptname」というidのカスタム投稿タイプの追加・編集・削除の権限を持つ「authid」というidの権限グループを追加できます。

<?php
function my_custom_post_type() {
	register_post_type(
		'ptname',
		array(
			'label' => 'カスタム投稿タイプ名',
			'public' => true,
			'capability_type' => 'ptauth',
			'has_archive' => true,
			'menu_position' => 5,
			'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields' ,'comments' )
		)
	);
	$rm = new WP_Roles();
	$rm->add_role("authid", "権限名" );
	foreach( array( "authid",  "administrator" ) as $rid ) {
		$role = $rm->get_role($rid);
		$role->add_cap("read");
		$role->add_cap("add_ptauth");
		$role->add_cap("add_ptauths");
		$role->add_cap("edit_ptauth");
		$role->add_cap("edit_ptauths");
		$role->add_cap("delete_ptauth");
		$role->add_cap("delete_ptauths");
		$role->add_cap("publish_ptauths");
	}
	$role->add_cap("delete_others_ptauths");
	$role->add_cap("edit_others_ptauths");
}
add_action( 'init', 'my_custom_post_type', 0 );

各関数の説明に関しては、以下のリンクを見ていただくと分かりやすいかと思います。

register_post_type

WP_Roles