0

I've been trying to figure out how to create a post (or any custom post type) with wp_insert_post() and AJAX...so far to no avail.

What I hope to achieve:

  • Any user (not just logged in ones, I don't want to mess with permissions for now) can create a post
  • To create the post I only want one input and one button and only the title can be created (other stuff is set default).

To start this I made a very simple plugin, here's the PHP; which...

  1. enqueues my JS
  2. attempts (and apparently fails) to create a function for inserting a post with wp_insert_post()
  3. has a super simple shortcode for displaying the field to use to create the post/initiate the AJAX.

/* Enqueue JS
----- */ 

function post_via_ajax_scripts() {  
    wp_register_script( 'post-via-ajax-js', plugin_dir_url( __FILE__ ) . 'post_via_ajax.js', array( 'jquery' ), '', true );
    wp_localize_script( 'post-via-ajax-js', 'pva_params', array( 'pva_ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'post-via-ajax-js' );
}
add_action('wp_enqueue_scripts', 'post_via_ajax_scripts');

//Add Ajax Actions
add_action('wp_post_via_ajax', 'post_via_ajax');
add_action('wp_post_via_ajax', 'post_via_ajax');

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

function post_via_ajax()
{

    $query_post_via_ajax = $_POST;
    $post_title = ($query_post_via_ajax['post_title']) ? $query_post_via_ajax['post_title'] : false;

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

    // Insert the post into the database
    wp_insert_post( $new_pva_post );
    exit();
};    
/* Form Shortcode
----- */ 

function post_via_ajax_shortcode( $atts, $content = null ) {
    return '<input id="post_title" name="post_title" type="text"><button id="create_post">Create Post</button>';
}

add_shortcode( 'post_via_ajax', 'post_via_ajax_shortcode' );

And here is my JS, which...

  1. has a very simple validation requiring the title to be more than 5 charachters
  2. attempts (and fails) to create the post via ajax and pass the 'post_title' to the post_via_ajax() function

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

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

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

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

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

            }
        })
    }
});

At this point I have no idea what I'm doing, so I would really appreciate any insights, if possible.

Thanks in advance!

  • do you have solution for adding Featured image along with ? Im facing issues with adding featured image and once the post is created show the url of the post – Vicky Parab Dec 18 '17 at 2:56
1

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.

Your Answer

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

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