Add a do_action to post_content of wp_insert_post

I created a plugin that is supposed to create a page with a contact form..

I got it to the point where it creates a page on activation of plugin, but I don’t know how to give the post_content a do_action..
Here is my create page function

function ap_post_creation() {
    global $wpdb;
    $user_id = get_current_user_id();

    //$content = do_action('show-ap-form');

    $args = array(
        'post_author' => $user_id,
        'post_content' => 'Hallo',
        'post_title' => 'Contact',
        'post_status' => 'publish',
        'post_type' => 'page',
        'comment_status' => 'closed',
    );

    wp_insert_post($args);
}

And here is my add_action function

<?php  
add_action('show-ap-form', 'show_ap_form');

function show_ap_form() {
    if(isset($_POST['submit'])) {

    }
?>
    <form method="post">
        <input type="text" name="name" placeholder="Enter your name">
        <input type="text" name="email" placeholder="Enter your e-mail">
        <textarea name="message" placeholder="Enter your message"> </textarea>
    </form>
<?php
}
?>

How can I attach the contact form to the newly created Contact page?

1 Answer
1

@Peter van der Net, here my approach, I create shortcode for newly created page. So we don’t have to save element form into database, and it make easy by user if they need move form to another page by shortcode. For submission, I use hook wp and handle data of form submission. For your issue, this is my simple code that you can figure it out.

function ap_post_creation() {
    $user_id = get_current_user_id();
    $args = array(
        'post_author'    => $user_id,
        'post_content'   => '[foobar]', //shortcode tag
        'post_title'     => 'Contact',
        'post_status'    => 'publish',
        'post_type'      => 'page',
        'comment_status' => 'closed',
    );
    wp_insert_post($args);
}

add_action( 'wp', 'show_ap_form' );
function show_ap_form( $wp ) {
    if ( isset( $_POST['submit'] ) ) {
        //run your stuff here don't forget to sanitize
    }
}

add_shortcode( 'foobar', 'ap_shortcode_form' );
function ap_shortcode_form( $atts ) {
    ob_start();
?>
    <form method="post">
        <input type="text" name="name" placeholder="Enter your name">
        <input type="text" name="email" placeholder="Enter your e-mail">
        <textarea name="message" placeholder="Enter your message"> </textarea>
        <button name="submit"><?php _e( 'Submit' ) ?></button>
    </form>
<?php
    $html_form = ob_get_clean();
    return $html_form;
}

Leave a Comment