add_post_meta when jQuery button is clicked

WordPress Ajax to the rescue! You’ll need to open up a function in WordPress that can be called via a javascript function, which is what the WP Ajax API was built for. It’s a bit of a multi-step process, but is quite powerful once you have it setup.

There’s a helpful article here that explains the overall concept of what you’re trying to accomplish, but the basics are:

  1. Expose admin-ajax.php to the front-end of your website, so your new script can hit it. Load something like the following in your theme’s functions.php:
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' );
  1. Create a function that will hit this endpoint and update the data you pass, again adding this to functions.php:
function increment_post_hearts() {
    $post_id = $_POST['post_id'];
    $current_hearts = get_post_meta( $post_id, 'heart');
    update_post_meta( $post_id, 'heart', $current_hearts++ ); //adds one to the heart count
    wp_die();
}

add_action( 'wp_ajax_nopriv_increment_post_hearts', 'increment_post_hearts' );

IMPORTANT: Note the “nopriv_” in the add_action call above. This lets users who are NOT logged in use the function. If instead you want only logged in users to hit this endpoint, remove the “nopriv_”. Rup’s comment on your initial question is very valid, as you may need to sort out how to prevent a user from hitting this more than once (if desired)

  1. Create the javascript that will actually run this function on a user’s click. Create a /js directory in your theme and add a file called “ajax-calls.js” with the following code (adjust to your use-case):
jQuery(document).ready( function($) {
    $('.class_of_your_heart_button').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
            }
        });
    });
});
  1. Finally, your button code for the front-end heart button should look something like the following:

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

Clicking on the button should fire the javascript call, passing in the post ID you’d like to +1 the heart count of. Your implementation may need some adjustments, but this should get you most of the way there.

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino