• Resolved shemakeswebsites

    (@shemakeswebsites)


    Hello, I am trying to run a check when a user visits a certain page to see if the current user has a published or draft posts of a custom post type. If they do, then I’m trying to redirect them. I’ve found some posts, but no luck in putting it all together to fit my needs. I can understand the template redirect function a bit easier, so I’ve tried to go that route. But I’m not sure if that’s the best way to do it.

    I’ve tried to work with these snippets:

    https://wordpress.stackexchange.com/questions/187973/how-to-check-that-if-current-user-id-has-posts-or-not

    https://wordpress.stackexchange.com/questions/139818/check-if-current-user-has-post-in-post-type-and-is-author-role

    Here’s what I’ve have so far:

    add_action( 'template_redirect', 'redirect_to_specific_page_resume' );
    
        function redirect_to_specific_page_resume() {
        global $post;
    
        $current_user = $post->post_author;
    
        if(!empty($current_user)){
        $user_post_count = (int) count_user_posts( $current_user );
    
           if ( is_page('479') && $user_post_count == 1 ) {
    
                wp_redirect( "/myaccount/manage-resumes", 301 ); 
    
                exit;
    
          }
       }        
       }

    This is what should happen:
    If current user goes to PAGE ONE and is a published or draft author of a custom post type, then redirect to PAGE TWO. If current user goes to PAGE ONE and is NOT a published author of a custom post type, do nothing, load PAGE ONE as normal.

    Thank you. ??

Viewing 1 replies (of 1 total)
  • Thread Starter shemakeswebsites

    (@shemakeswebsites)

    If anyone can use this, here’s the code

    Solution provided by [butlerblog][1]

    add_action( 'template_redirect', 'redirect_to_specific_page_resume' );
    
    function redirect_to_specific_page_resume() {
    
        /*
         * Only bother to check if the user is logged in 
         * AND we're on page ID 479. Otherwise, there's no
         * reason to run the remaining logic.
         */
        if ( is_user_logged_in() && is_page( 479 ) ) {
    
            // Get the current logged in user's ID
            $current_user_id = get_current_user_id();
    
            // Count the user's posts for 'resume' CPT
            $user_post_count = (int) count_user_posts( $current_user_id, 'resume' );
    
            // If the user has a 'resume' CPT published
            if ( $user_post_count > 1 ) {
    
                // Get the URL to redirect the user to.
                $url = get_permalink( 480 );
    
                // Redirect the user.
                wp_redirect( $url ); 
                exit();
    
            }
        }
    }
    

    [1]: https://wordpress.stackexchange.com/users/38603/butlerblog

Viewing 1 replies (of 1 total)
  • The topic ‘Redirection help’ is closed to new replies.