How To Update WordPress Posts With AJAX On The Front-End

Looking to update posts, including custom post types on your WordPress website’s front-end through AJAX? This WordPress guide explains it all.

Updating posts with AJAX on front-end

To update your WordPress post’s meta-data on the front-end of your website, we must use AJAX to achieve this.

Using admin-ajax.php and loading scripts

In your WordPress theme’s functions.php file, we need to call the wp_localize_script(); function to grab admin-ajax.php and also wp_enqueue_script(); to load our AJAX calls.

function add_ajax_scripts() {
    wp_enqueue_script( 'ajaxcalls', get_template_directory_uri() . '/js/ajax-calls.js', array(), '1.0.0', true );

    wp_localize_script( 'ajaxcalls', 'ajax_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' )
    ) );
}

add_action( 'wp_enqueue_scripts', 'add_ajax_scripts' );

Creating the front-end update function

When creating the function, we need to confirm the post’s ID in order to update the meta-data.

function custom_update_post() {
    $post_id = $_POST['post_id'];
    update_post_meta( $post_id, 'your_meta_key', 'Your New Value' );
    wp_die();
}

add_action( 'wp_ajax_custom_update_post', 'custom_update_post' );

Note, to use this on logged-out-mode; you need to use wp_ajax_nopriv_your_function when adding the action.

Creating ajax-calls.js

As you can remember from when calling wp_enqueue_script(); above, we created a JavaScript file in your theme’s js folder. Simply create this file (ajax-calls.js) and amend the correlating path in your theme.

After you’ve done this, paste in the following AJAX code.

jQuery(document).ready( function($) {
    $('.your_class_to_update').on('click', function() {
        var post_id = $(this).attr( 'id' );
        $.ajax({
            type: 'POST',
            url: ajax_object.ajaxurl,
            data: {
                action: 'custom_update_post',
                post_id: post_id
            }
        });
    });
});

Passing in the ID

To pass the ID into the script, you need to have the ID of .your_class_to_update set to your post’s ID using the get_the_ID(); WordPress function.

<button id="<?php echo get_the_ID(); ?>" class="your_class_to_update">Click To Update</button>