0

This is my first time creating a plugin for WordPress and I'm trying to create a plugin for Front-end form for logged in users. So far, the front-end form shows up on a page with a shortcode [write-here] and I check data goes into DB but there are couple things not working properly.

  1. post_author does not get any value (According to this codex, it sets current user as default but no value goes into DB)

  2. No return $post_id. I can't get the post ID return value after submitting the form.

  3. Redirect is not working (This is probably becuase of wp_insert_post not working properly. Seems like nothing works after wp_insert_post)

Here is the code I have so far.

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
// Define plug-in path
define('WH_PATH', plugins_url() . '/write-here');
// Load css & js files
function my_enqueued_assets() {
    wp_enqueue_style( 'write-here', WH_PATH . '/css/write-here.css' );
    wp_enqueue_script( 'write-here', WH_PATH . '/js/write-here.js', array( 'jquery' ), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueued_assets' );
/*
**  Add front end from in a Shortcode
    https://codex.wordpress.org/Function_Reference/add_shortcode
*/
function form_write_here(){
    $postdate = date('Y-m-d H:i:s');

    // Show only to logged in users
    if ( is_user_logged_in() ) {
?>
    <div class="write-here">
        <form id="new_post" name="new_post" method="post" action="">
            <label for="title">Title</label>
            <input type="text" id="title" name="title" />

            <label for="content">Content</label>
            <textarea id="content" name="content" rows="6"></textarea>

            <label for="cat">Category</label>
            <?php wp_dropdown_categories( 'show_option_none=Category&taxonomy=category&hide_empty=0' ); ?>

            <label for="post_tags">Tags</label>
            <input type="text" id="post_tags" name="post_tags" />

            <label for="date">Date</label>
            <input type="text" value="<?php echo $postdate; ?>" id="date" name="date" />

            <input type="submit" value="Publish" id="submit" name="submit" />
            <input type="hidden" name="action" value="write_here_new_post" />
            <?php wp_nonce_field( 'new-post' ); ?>
        </form>
    </div>
<?php
    }else{
        echo 'Please Sign in to continue...';
    }
}
add_shortcode('write-here', 'form_write_here');
/*
**  Process data from front end form
    http://codex.wordpress.org/Function_Reference/wp_insert_post
*/
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "write_here_new_post") {
    // Do some minor form validation to make sure there is content
    if ($_POST['title']) {
        $title =  wp_strip_all_tags($_POST['title']);
    } else {
        echo 'Please enter a title';
    }
    if ($_POST['content']) {
        $content = $_POST['content'];
    } else {
        echo 'Please enter the content';
    }
    if ($_POST['date']) {
        $postdate = $_POST['date'];
    } else {
        $postdate = date('Y-m-d H:i:s');
    }
    $tags = $_POST['post_tags'];
    $cat  = $_POST['cat'];
    // Add the content of the form to $post as an array
    $new_post = array(
        'post_title'    => $title,
        'post_content'  => $content,
        'post_category' => array($cat),   // Default empty.
        'tags_input'    => array($tags),    // Default empty.
        'post_status'   => 'publish',       // Choose: publish, preview, future, draft, etc. Default 'draft'.
        'post_date'     => $postdate,      // The time post was made.
        'post_date_gmt' => $postdate       // The time post was made, in GMT.
    );
    //save the new post and return its ID
    $post_id = wp_insert_post($new_post, $wp_error ); // this not working
    // redirect after submition
    wp_redirect( site_url()."?post=".$post_id);
    exit();
}

Feel free to make comments for any suggestions as well. Thank you!

1 Answer 1

0

Updating answer for people who might have same issue as me.

I wrapped up front end form and the code to execute the date from the form into functions and it started to work.

I also added additional functions for loading CSS/JS files only on the page where plugin is being used. Along with error message function.

Here is the new code

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

// Define plug-in path
define('WH_PATH', plugins_url() . '/write-here');


/*
** Register CSS & JS assets for plug in
------------------------------------------------------------------
*/
// register our form css
function write_here_register_assets() {
    wp_register_style('write-here', WH_PATH . '/css/write-here.css');
    wp_register_script( 'write-here', WH_PATH . '/js/write-here.js', array( 'jquery' ), '1.0', true );
}
add_action('init', 'write_here_register_assets');

// load our form css
function write_here_print_assets() {
    global $write_here_load_assets;

    if ( !$write_here_load_assets )
        return;

    wp_print_styles('write-here');
    wp_print_scripts('write-here');
}
add_action('wp_footer', 'write_here_print_assets');


/*
**  Add a shortcode for front end form
    https://codex.wordpress.org/Function_Reference/add_shortcode
*/
function form_write_here(){
    // Load CSS & JS files
    global $write_here_load_assets;
    $write_here_load_assets = true;

    // Show only to logged in users
    if ( is_user_logged_in() ) {
        $output = write_here_form();
        return $output;
    }else{
        echo 'Please Sign in to continue...';
    }
}
add_shortcode('write-here', 'form_write_here');


/*
**  Front end From
    ------------------------------------------------------------------
*/
function write_here_form(){
    ob_start();
    $postdate = date('Y-m-d H:i:s');
?>
<div class="write-here">
    <?php write_here_show_error_messages(); ?>
    <form id="new_post" name="new_post" method="post" action="">
        <label for="title">Title</label>
        <input type="text" id="title" name="title" />

        <label for="content">Content</label>
        <textarea id="content" name="content" rows="6"></textarea>

        <label for="cat">Category</label>
        <?php wp_dropdown_categories( 'show_option_none=Category&taxonomy=category&hide_empty=0' ); ?>

        <label for="post_tags">Tags</label>
        <input type="text" id="post_tags" name="post_tags" />

        <label for="date">Date</label>
        <input type="text" value="<?php echo $postdate; ?>" id="date" name="date" />

        <input type="submit" value="Publish" id="submit" name="submit" />
        <input type="hidden" name="action" value="write_here_new_post" />
        <?php wp_nonce_field( 'new-post' ); ?>
    </form>
</div>
<?php  
    return ob_get_clean();
}


/*
**  Process data from front end form
    http://codex.wordpress.org/Function_Reference/wp_insert_post
*/
function write_here_add_new_post() {
    if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "write_here_new_post") {

        $title =  wp_strip_all_tags($_POST['title']);
        $content = $_POST['content'];
        $postdate = $_POST['date'];
        $tags = $_POST['post_tags'];
        $cat  = $_POST['cat'];

        // Do some minor form validation to make sure there is content
        if ($title == '') {
            write_here_errors()->add('title_not_vaild', __('Title not valid'));
        }
        if ($content == '') {
            write_here_errors()->add('content_not_vaild', __('Content not valid'));
            return false;
        }
        if (!$postdate) {
            $postdate = date('Y-m-d H:i:s');
        }

        // Add the content of the form to $post as an array
        $new_post = array(
            'post_title'    => $title,
            'post_content'  => $content,
            'post_category' => array($cat),   // Default empty.
            'tags_input'    => array($tags),    // Default empty.
            'post_status'   => 'publish',       // Choose: publish, preview, future, draft, etc. Default 'draft'.
            'post_date'     => $postdate,      // The time post was made.
            'post_date_gmt' => $postdate       // The time post was made, in GMT.
        );

        $errors = write_here_errors()->get_error_messages();

        // only create post if there are no errors
        if(empty($errors)) {
            //save the new post and return its ID
            $post_id = wp_insert_post($new_post);

            if($post_id) {
                // This will redirect you to the newly created post (Using GUID)
                $post = get_post($post_id);
                wp_redirect($post->guid);
                exit();
            }
        }
    }
}
add_action('init', 'write_here_add_new_post');

// used for tracking error messages
function write_here_errors(){
    static $wp_error; // Will hold global variable safely
    return isset($wp_error) ? $wp_error : ($wp_error = new WP_Error(null, null, null));
}

// displays error messages from form submissions
function write_here_show_error_messages() {
    if($codes = write_here_errors()->get_error_codes()) {
        echo '<div class="form-error">';
        // Loop error codes and display errors
        foreach($codes as $code){
            $message = write_here_errors()->get_error_message($code);
            echo '<span class="error"><strong>' . __('Error') . '</strong>: ' . $message . '</span><br/>';
        }
        echo '</div>';
    }   
}

Please feel free to make comments for any suggestions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.