Skip to content

Disable Editing for Speicified Pages for Some Users only

Using WordPress mehtods via capabilities is the best way to achieve this. Hiding the elements in the backend still shows the admin bar edit link. also hiding is not good practice. WordPress provides a good capability system. So if you manage capabilities WordPress will do rest for you.

function check_allow_edit ( $caps, $cap, $user_id, $args ) {

	$to_filter = [ 'edit_post', 'delete_post', 'edit_page', 'delete_page' ];

	// If the capability being filtered isn't of our interest, just return current value
	if ( ! in_array( $cap, $to_filter, true ) ) {
		return $caps;
	}
	
	// First item in $args array should be page ID
	$page_id = $args[0];
	$page = get_post( $page_id );

	/*
	if ( ! $current_page_id ) {
		//cannot edit
		$can_edit = false;
	}
	*/
	if ($page->post_parent)	{
		$ancestors = get_post_ancestors($page->ID);
		$root = count($ancestors)-1;
		$page_id = $ancestors[$root];
	}

	if ($user_id == 137) {

		$allowed_ids = array('37');

		if (in_array($page_id, $allowed_ids)) {
			//user 1 and current page is allowed - can edit
			$can_edit = true;
		} else {
			//user 1 and current page is not allowed - cannot edit
			$can_edit = false;
		}

	} else {
		//not the specified user so edit all
		$can_edit = true;
	}

	// First item in $args array should be page ID
	//if ( ! $args || empty( $args[0] ) || ! wpse_user_can_edit( $user_id, $args[0] ) ) {
	if ( ! $args || empty( $args[0] ) || $can_edit == false ) {	
		// User is not allowed, let's tell that to WP
		return [ 'do_not_allow' ];
	}
	// Otherwise just return current value
	return $caps;

};

add_filter( 'map_meta_cap', 'check_allow_edit', 10, 4 );

Via

Dieser Beitrag hat 0 Kommentare

Schreibe einen Kommentar

Deine E-Mail wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

An den Anfang scrollen