WordPressのデータをAjax通信を用いて取得するためには、WordPressのfunctions.phpとブラウザ側(index.htmlなど)に以下の処理を加えます。
<functions.php>
function my_ajax_get_posts(){
$returnObj = array();
//配列$returnObjを宣言
//取得するデータの指定
$args = array(
'post_type' => 'post',//投稿タイプ
'numberposts' => 100,//取得する投稿の数を指定
);
$posts = get_posts( $args );
//配列$returnObjに投稿データを格納
foreach( $posts as $key => $post ) {
$returnObj[$key] = array(
'post_title' => $post->post_title,//ページタイトル
'permalink' => get_permalink( $post->ID ),//投稿ページのURL
'adress' => get_post_meta( $post->ID, '{カスタムフィールドのキー}' , true),//指定したキーのカスタムフィールドの値の取得 ); }
echo json_encode( $returnObj ); die();
} add_action( ‘wp_ajax_my_ajax_get_posts’, ‘my_ajax_get_posts’ ); add_action( ‘wp_ajax_nopriv_my_ajax_get_posts’, ‘my_ajax_get_posts’ );
<index.html>
jQuery(function($) { $.ajax({ type: “POST”, url: “http://{自分の名前}.local/wp-admin/admin-ajax.php”,//処理の命令先のパスの指定 data: { action: “my_ajax_get_posts” }, success: function(response) { jsonData = JSON.parse(response); //受け取ったデータをコンソール上に表示 $.each(jsonData, function(i, val) { console.log(val[“post_title”]); console.log(val[“permalink”]); console.log(val[“adress”]); }); } }); return false; });


