php – Restrict post to current user in postmeta

Question

i hope someone can help, i’m have not php skill, try with some sample without success.

i have a CPT with metafield “email” where stored user email .
does its possible to restrict post url for these post.

i mean.. opening cpt url , if user is logged-in and postmeta (inside the post) = current_user_email .. post is opening, otherwise redirect to /account.

many thanks
(The snippet is working, i ask you for better review)

add_action( 'template_redirect', 'redirect_different_post_meta' );

function redirect_different_post_meta() {
       $current_user = wp_get_current_user();
       $currentemail = $current_user->user_email;
        global $post;
    if(!current_user_can('administrator')) {

     if ( $post->post_type == 'cpt_slug' ) {
      
      $postemail = get_post_meta($post->ID, 'email', true);
    
       if($currentemail != $postemail) {
       wp_safe_redirect( '/my-account' , $status = 302 );
        exit;
        } 
     
    }
}

0
Fabio 2 weeks 2022-08-01T16:51:58-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse