JiveDig
10/19/2015 - 1:59 PM

Creates a shortcode to conditionally display a form if the current user is the author of the post they're trying to edit.

Creates a shortcode to conditionally display a form if the current user is the author of the post they're trying to edit.

<?php
/**
 * Shortcode to conditionally display a post edit form
 *
 * @author  Mike Hemberger
 * @link    http://thestizmedia.com/front-end-post-editing-with-caldera-forms/
 * @uses    Caldera Forms
 * @return  mixed Access message or Caldera Form
 */
add_shortcode( 'edit_post', 'tsm_do_caldera_edit_post_form' );
function tsm_do_caldera_edit_post_form() {

    // Bail and show message if not logged in
    if ( ! is_user_logged_in() ) {
        $output = __( 'You must be logged in to edit posts.', 'caldera-forms' );
    }

    // Check if post_id query arg is set, and if it's greater than 0
    if ( isset( $_GET['post_id'] ) ) {

        // Get post object from query arg
        $post_object = get_post( $_GET['post_id'] );

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

            // If current user is the same as the editing post ID
            if ( get_current_user_id() === (int)$post_object->post_author ) {
                // Display 'Edit Post' Caldera Form
                $output = Caldera_Forms::render_form('Edit Post'); // Replace 'Edit Post' with your form name or ID
            } else {
                // User is not the author of the post they're trying to edit
                $output = __( 'You must be the author to edit this post/page.', 'caldera-forms' );
            }

        } else {
            // The ID given is not a valid post object
            $output = __( 'Whoops, looks like there\'s no post for you to edit!', 'caldera-forms' );
        }

    } else {
        // There was no ID given to edit
        $output = __( 'Whoops, looks like there\'s no post for you to edit!', 'caldera-forms' );
    }

    return $output;

}