0

I want to allow logged-in any users to create posts. For this purpose I created a form

<form>

    <div class="form-group">
        <input type="text" class="form-control" id="post_title" placeholder="Title">
    </div>

    <div class="form-group">
        <textarea class="form-control" id="post_content" rows="10" placeholder="Content should go here..."></textarea>
    </div>

    <button type="submit" class="btn btn-primary" >Submit your post</button>

</form>

I was following WP_INSERT_POST but I am confused about the hook and finally I hooked it in ADMIN_INIT (just from guesses) and here the code in functions.php

function test_insert_post_function() {
    $postarr = array(
        'post_title'    => $_POST['post_title'],
        'post_content'  => $_POST['post_content'],
        'post_status'   => 'publish',
        'post_author'   => get_the_author_meta('ID'),
        'post_category' => array(1)
    );
    wp_insert_post( $postarr );
}
add_action('admin_init', 'test_insert_post_function');

Now I am not finding a way to make a relation between the submit-button & this Function

Here is the theme files: https://bitbucket.org/shihab0915/twentyfifteen-child/src

And here is the temporary live URL: https://nullified-nuts.000webhostapp.com/

I found few similar questions here but those were asked & answered 6/7 years ago.

So how can I achieve this goal?

  • Is there a reason you're not just letting the authenticated users add posts using the editor in wp-admin? – WebElaine Sep 17 '18 at 18:49
  • Yes, I want them to post via front-end form. – shihab Sep 17 '18 at 18:58
  • Ok, the issue is you're trying to hook your function to the admin area when instead you need to POST the post details directly to your script. Remove your admin_init hook and instead set the form action to the URL of your PHP plugin file. Then, in the plugin, check for the required POST parameters and use wp_insert_post(). – WebElaine Sep 17 '18 at 19:40
  • Sorry, I am not using any plugin. Just created a child-theme of twentyfifteen. – shihab Sep 17 '18 at 19:49
  • 1
    I would note that the code here will create a brand new post on every single request to the admin area, that is the literal interpretation of what your code does. There's no "when the user submits the form" if statement, and none of the code runs on the frontend. I would start off by implementing a very, very basic form to get to grips with how frontend form handling is supposed to work, e.g. something that just says "Success!" when you submit the form, then introduce the wp_insert_post etc – Tom J Nowell Sep 17 '18 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.