Create Page With wp_insert_post() and AJAX

Ok, so after some fiddling, I’ve got things working.

It turns out that I was setting the add_action hooks incorrectly for the AJAX part.

The hooks need to be:

add_action( 'wp_ajax_nopriv_MYFUNCTION', 'MYFUNCTION' );

and

add_action( 'wp_ajax_MYFUNCTION', 'MYFUNCTION' );

…in my case and original code the function (‘MYFUNCTION’) in question was to create a post via wp_insert_post().

So, after cleaning up my namin conventions and code a bit, I have the following:

PHP

/**
 Plugin Name: Post via Ajax
 */

/* Enqueue JS
----- */ 

function pva_scripts() {
    wp_register_script( 'pva-js', plugin_dir_url( __FILE__ ) . 'pva.js', array( 'jquery' ), '', true );
    wp_localize_script( 'pva-js', 'pva_params', array( 'pva_ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'pva-js' );
};

add_action('wp_enqueue_scripts', 'pva_scripts');

// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_pva_create', 'pva_create' );
add_action( 'wp_ajax_pva_create', 'pva_create' );

/* WP Insert Post Function
----- */ 

function pva_create()
{

    $post_title = $_POST['post_title'];

    // Create post object
    $new_pva_post = array(
        'post_type'     => 'page',
        'post_title'    => $post_title,
        'post_status'   => 'publish',
        'post_author'   => 1,
    );

    // Insert the post into the database
    wp_insert_post( $new_pva_post );
    exit();
};



/* Form Shortcode
----- */ 

function pva_shortcode( $atts, $content = null ) {
    ob_start();
    include(plugin_dir_path( __FILE__ ) . 'post_via_ajax_field.php');
    $ret = ob_get_contents(); 
    ob_end_clean(); 
    return $ret;
        //pva();
};

add_shortcode( 'pva', 'pva_shortcode' );

JS


jQuery( document ).ready( function ( $ ) {

    $('#create_post').attr('disabled',true);
    $('#post_title').keyup(function(){
        if($(this).val().length > 3) {
            $('#create_post').attr('disabled', false);
        } else {
            $('#create_post').attr('disabled',true);    
        }
    });

    $('#create_post').click(function(event){
        post_via_ajax();
    });

    // Return Post Title Field Value
    function returnNewPostTitle(){
        var newPostTitleValue = $('#post_title').val();
        return newPostTitleValue;
    }

    // AJAX > Get City Posts
    function post_via_ajax()
    {
        var pva_ajax_url = pva_params.pva_ajax_url;

        $.ajax({
            type: 'POST',
            url: pva_ajax_url,
            data: {
                action: 'pva_create',
                post_title: returnNewPostTitle()
            },
            beforeSend: function ()
            {
                console.log('sending');
            },
            success: function(data)
            {
                console.log('yay');
            },
            error: function()
            {
                console.log('nay');

            }
        })
    }
});

So, with this as a plugin and using the shortcode [pva], you can create a post from the front-end. Obviously this was only intended to be quite basic so I’d imagine you could adapt/adjust to your needs. Hope this helps someone. 🙂

EDIT: I also just made a super basic GitHub repo with the code.