Loading WordPress metakeys with AJAX

at the moment my theme I load posts with AJAX. But how can I can get also post meta keys via AJAX?

At the moment functions PHP is like this:

Read More
add_action('wp_ajax_nopriv_ajax_action', 'ajax_loading');
add_action('wp_ajax_ajax_action', 'ajax_loading');

function ajax_loading() {
    switch($_REQUEST['fn']) {
        case 'get_latest_posts':
        $output = ajax_get_latest_posts($_REQUEST['count']);
        break;
        default:
        $output = 'Error. No function specified.';
        break;
    }
    $output = json_encode($output);
    if (is_array($output)) {
        print_r($output);
    }
    else {
        echo $output;
    }
    die;
}

function ajax_get_latest_posts($count) {
     $posts = get_posts('numberposts='.$count.'&post_status=publish');

     return $posts;
}

And jQuery:

$.ajax({
        url: 'http://domain.com/wp-admin/admin-ajax.php',
        type: 'POST',
        data: {
            'action': 'ajax_action',
            'fn': 'get_latest_posts',
            'count': 15
        },
        dataType: 'JSON',
        success:function(data){
            //print stuff here
        },
        error: function(errorThrown){
            //error stuff here
        }
    })

With these code i only get the main post info (title, id, date, content…).

So have anyone tried to get meta keys/values with AJAX/JS from posts?

Related posts

Leave a Reply

1 comment

  1. You can tweak your ajax_get_latest_posts() function to something like this:

    function ajax_get_latest_posts($count) {
      $posts = get_posts('numberposts='.$count.'&post_status=publish');
    
      foreach ($posts as $key => $post) {
        $posts[$key]->meta = get_post_meta($post->ID);
      }
    
      return $posts;
    }
    

    I’ve added a ‘meta’ key to each posts using get_post_meta()