1

目前我的主题是用 AJAX 加载帖子。但是我怎样才能通过 AJAX 获得发布元密钥?

目前PHP的功能是这样的:

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;
}

和 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
        }
    })

使用这些代码,我只能获得主要的帖子信息(标题、ID、日期、内容......)。

那么有没有人尝试过使用 AJAX/JS 从帖子中获取元键/值?

4

1 回答 1

1

您可以将ajax_get_latest_posts()功能调整为如下所示:

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;
}

posts使用get_post_meta()为每个添加了一个“元”键

于 2013-06-20T11:41:07.180 回答