How to check that if current user (ID) has posts or not

Notice that your redirection must happen before the HTTP headers are sent out.

You can try the following, where we place our logic inside the template_redirect hook callback (PHP 5.4+):

/**
 * Redirect logged-in users to the admin dashboard 
 * if the have written 'student_form' posts
 * else display [wpuf_form id="414"]
 */

add_action( 'template_redirect', function()
{
    if( ! is_user_logged_in() )
        return;

    if( wpse_current_user_has_posts( 'student_form' ) )
    {
        // Redirect to the admin dashboard:
        wp_safe_redirect( admin_url() );  // Edit to your needs!
        exit();
    }
    else
    {
        // Note that here you might instead do a redirect to a page containing that shortcode.
        get_header();
        echo do_shortcode( '[wpuf_form id="414"]' );
        get_footer();
        exit();
    }

} );

where we use this helper function:

/**
 * Check if the current user has written any posts in a given post type
 * 
 * @param string $post_type
 * @return bool
 */    
function wpse_current_user_has_posts( $post_type="post" )
{
    $posts = [];
    if( $uid = get_current_user_id() )
    {
        $posts = get_posts( 
            [ 
                'posts_per_page' => 1, 
                'post_type'      => sanitize_key( $post_type ), 
                'author'         => $uid,
                'fields'         => 'ids'
            ]
        );
    }
    return 0 < count( $posts );
}

Leave a Comment