Fetch and show multiple custom fields via AJAX

I am trying to fetch custom field values from database and show them on page. I am able to do that for single custom field but not sure how to do that with multiple values at once.

Here is my function for getting latest value of price custom field.

function get_latest_price() {
    if ( !isset($_GET['post_id']) || empty($_GET['post_id']) ) {
        die( '0' );
    }
    $post_id = intval( filter_var( $_GET['post_id'], FILTER_SANITIZE_NUMBER_INT ) );
    if( empty($post_id) ) {
        die( '0' );
    }
    $latest_price = get_post_meta( $post_id, 'latest_price', true );
    die( strval( $latest_price ) );
}
add_action( 'wp_ajax_nopriv_ajax-get-latest-price', 'get_latest_price' );
add_action( 'wp_ajax_ajax-get-latest-price', 'get_latest_price' );

And this is the JavaScript.

$(document).ready( function() {
    $.ajax({
        type : "GET",
        url : ajax_object.ajaxurl,
        data : { action : "ajax-get-latest-price" },
        success: function ( result ) {
            $('span.price').html( result );
        }
    });
});

This works for one field but I need to update ~10 fields on front end and I know that adding similar PHP functions for each of 10 fields can do the job but I don’t think it’s efficient way to do that.

We can get all meta keys in PHP array with get_post_meta( get_the_ID() ); but how to go from there and update following HTML tags.

<span class="price"></span>
<span class="exp-date"></span>
<span class="seller"></span>
<span class="location"></span>
...
<span class="item-10"></span>

1 Answer
1

To pass data from js back to PHP simplest way is use json_encode or, in WP, its wrappers wp_send_json, wp_send_json_error and wp_send_json_success.

Usage example:

On PHP side

function get_latest_product_meta() {

    $post_id = (int) filter_input(INPUT_GET, 'post_id', FILTER_SANITIZE_NUMBER_INT);
    $post_id or wp_send_json_error();

    // array_shift because when used like so `get_post_meta` return array of arrays...
    $data = array_map('array_shift', get_post_meta($post_id));
    wp_send_json_success($data);
}

On js side

$(document).ready( function() {
    $.ajax({
        type : "GET",
        url : ajax_object.ajaxurl,
        data : { action : "ajax-get-latest-price" },
        success: function ( result ) {
            if (result.error) {
               alert('Post not found!');
            } else if(result.success) {
               $('span.price').html( result.data.price );
               $('span.seller').html( result.data.seller);
               // and so on....
            }
        }
    });
});

Leave a Comment