TsiartasM
TsiartasM

Reputation: 11

How to Update Post Meta with AJAX

I have created a website initializing CMB2 for custom post types, fields, metaboxes etc. I have created a Custom Checkbox Field which acts like a Flag. Checked or Unchecked. This Checkbox rests in a Custom Post Type Metabox and is visible on the backend.

What we need to achieve is have a Button on the Front End for the User to click. When the button is clicked, the value of the checkbox should change (update_post_meta for this checkbox).

I suppose this should be done with AJAX, but got no previous experience with it.

This is where the code should go. It checks if the Checkbox is checked, if it is checked then it just output the . If it is not checked, it should output the Button that would toggle the checkbox status.

<?php $adopted_check = get_post_meta( get_the_ID(), INVENTOR_LISTING_PREFIX . 'adopted-check', true ); ?>
                    <?php if ( $adopted_check ) { ?>
                             <div class="adopted"><i class="fa fa-thumbs-up" style="font-size: 20px;"></i><span><?php echo esc_attr__( 'Adopted', 'inventor' ); ?></span></div>
                        <?php } else { ?>
                        <button type="submit">Mark as Adopted</button>
                    <?php } ?>

Can anyone help with this?

Upvotes: 1

Views: 1918

Answers (1)

Hitesh Kumar
Hitesh Kumar

Reputation: 103

You can create an ajax call like this in jQuery

$.ajax({
            type: "POST",
            url: ajaxurl,
            async:true,
            data: { 
                action: 'callback_action', 
                security: $('#security').val(),
                custom_info:custom_info
            },
            cache: false,
        });

Now wordpress will automatically catch the action with wp_ajax_ action for example:

add_action('wp_ajax_callback_action','function_name');
function function_name(){
$security = $_POST['security'];
$custom_info = $_POST['custom_info'];
// your code goes here to update the meta
die()// It's necessary to add die at the end of an ajax call or it will return 0.
}

Done.

Upvotes: 1

Related Questions