3

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

4

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....
            }
        }
    });
});
5
  • Thanks gmazzap but it's not doing anything. I also tried to add log in console but it does not show anything.
    – Robert hue
    Jul 7, 2015 at 20:15
  • @Roberthue There was a typo. Fixed.
    – gmazzap
    Jul 7, 2015 at 21:24
  • Yes it's working now. Thank you very much. I have been struggling with JSON whole morning. I have one more question. This works great on single page. But what can I do to update some of these custom fields on posts list page. Post list page will have nearly 10 posts and each of those have 2-3 fields that need updating of information with AJAX.
    – Robert hue
    Jul 7, 2015 at 21:40
  • @Roberthue WP has no functions to get meta from more than one post. You need a custom DB query. Then pass back results to js using same method as above and manipulate the array from js. You need to know which data belongs to which post, and so you'll probably add need to add id attribute to your HTML markup based on post id. I can't explain better than this in a comment.
    – gmazzap
    Jul 7, 2015 at 21:53
  • It looks like a resource exhausting task to gain very little. I will leave posts list page for now. Thanks for the above solution, it's really awesome.
    – Robert hue
    Jul 7, 2015 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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