If you search how to add content view restrictions for post programmatically it’s a right place.
Look at user-role-editor-pro/pro/includes/classes/content-view-restrictions-editor.php
file. Class has public function which allows to save view restrictions for post by its ID. You may call it like below:
URE_Content_View_Restrictions_Editor::save_post_meta_data( $post_id );
One inconvenience – code is written to get values to save from the $_POST array. So you have to manually build this array before try to save for post.
- $_POST[‘ure_prohibit_allow_flag’] : int, 1 – prohibit, 2 – allow;
- – ure_content_view_whom : 1 – all, 2 – logged in only, 3 – selected roles;
- ure_content_for_roles : comma separated string of roles ID, use in case ure_content_view_whom=3;
- ure_post_access_error_action : 1 – 404 HTTP, 2 – show default access error message, 3 – show error message for this post, 4 – redirect to URL;
- ure_post_access_error_message : string with custom access error message for this post, use in case ure_post_access_error_action=3;
- ure_view_access_error_url : string with URL where to redirect, use in case ure_post_access_error_action=4;
You may use URE_Content_View_Restrictions_Editor::save_meta_data() as a starting point to write code especially for your need. URE stores post level content view restrictions as the post meta using custom constants as the meta key ID. For example:
update_post_meta( $post_id, URE_Content_View_Restrictions::PROHIBIT_ALLOW_FLAG, $ure_prohibit_allow_flag );
update_post_meta( $post_id, URE_Content_View_Restrictions::CONTENT_VIEW_WHOM, $content_view_whom );
if ($content_view_whom==3) { // for selected roles
update_post_meta( $post_id, URE_Content_View_Restrictions::CONTENT_FOR_ROLES, $ure_content_for_roles1 );
}
update_post_meta( $post_id, URE_Content_View_Restrictions::POST_ACCESS_ERROR_ACTION, $ure_post_access_error_action );
if ( $ure_post_access_error_action==3 ) { // custom access error message
update_post_meta( $post_id, URE_Content_View_Restrictions::POST_ACCESS_ERROR_MESSAGE, $ure_post_access_error_message );
}
if ( $ure_post_access_error_action==4 ) { // Redirect to URL
self::update_post_meta( $post_id, URE_Content_View_Restrictions::ACCESS_ERROR_URL, $view_access_error_url );
}