JiveDig
10/19/2015 - 2:07 PM

Helper function to check if the currently logged in user is the author of a specific post, by post ID

Helper function to check if the currently logged in user is the author of a specific post, by post ID

<?php

/**
 * Helper function to check if a user is the author of a specific post
 *
 * @author  Mike Hemberger
 * @link    http://thestizmedia.com/front-end-post-editing-with-caldera-forms/
 * @param   int  $post_id  Post ID
 * @return  bool
 */
function tsm_is_current_users_post( $post_id ) {

    // Bail if user is not logged in
    if ( ! is_user_logged_in() ) {
        return false;
    }
    
    // Consider adding a current_user_can() conditional here as well

    // Get the post object
    $post_object = get_post( $post_id );

    // If is an object and no errors
    if ( is_object( $post_object ) && ! is_wp_error( $post_object ) ) {

        // Return true if currently logged in user ID is the same as the editing post ID
        if ( get_current_user_id() === (int)$post_object->post_author ) {
            return true;
        }
    }
    return false;
}