However,would also be good to know how to do this for a post type also.
You and your decisions. just change page to the post type in "page" == $post->post_type
in the code..
Add the following code as a custom plugin or to your child theme’s functions file:
/*
Plugin Name: Marking pages invisible
Plugin URI:
Description: Marking pages invisible
Author: Samuel Elh
Version: 0.1
Author URI: https://samelh.com
*/
add_action('wp', function() {
if( is_singular() && is_user_logged_in() ) :;
global $post;
$user = wp_get_current_user();
if( "page" == $post->post_type ) {
$meta = get_user_meta( $user->ID, '_not_visible_pages', 1 );
$meta = explode( ',', $meta );
if( in_array( $post->ID, $meta ) ) {
wp_redirect( home_url('?se_rdr') );
exit;
}
}
endif;
return;
});
add_filter('the_content', function( $content ) {
if( is_singular() && is_user_logged_in() ) {
global $post;
if( "page" == $post->post_type ) {
ob_start();
?>
<form method="post" onsubmit="return confirm('Are you sure?')" class="se_miv">
<?php wp_nonce_field('se_miv', 'se_miv'); ?>
<input type="hidden" name="post_id" value="<?php echo $post->ID; ?>" />
<input type="submit" name="se_mark_invisible" value="Mark as invisible" />
</form>
<?php
$content .= ob_get_clean();
}
}
return $content;
});
add_action('init', function() {
if( ! is_user_logged_in() || ! isset( $_POST['se_mark_invisible'] ) || ! isset( $_POST['se_miv'] ) || ! wp_verify_nonce( $_POST['se_miv'], 'se_miv' ) ) { return; }
$user = wp_get_current_user();
$pid = (int) $_POST['post_id'];
$meta = get_user_meta( $user->ID, '_not_visible_pages', 1 );
$meta = explode( ',', $meta );
array_push($meta, $pid);
$meta = array_filter( array_unique( $meta ) );
update_user_meta( $user->ID, '_not_visible_pages', implode(',', $meta) );
wp_redirect( home_url('?se_miv=1') );
exit;
});
add_action('wp_footer', function() {
if( isset( $_GET['se_rdr'] ) ) {
?>
<script type="text/javascript">window.onload=function(){alert('Page not accessible')}</script>
<?php
} elseif( isset( $_GET['se_miv'] ) ) {
?>
<script type="text/javascript">window.onload=function(){alert('Page successfully marked invisible.')}</script>
<?php
}
});
https://pastebin.com/zXwufYSR