WordPressのカスタムフィールドの値を使用してカスタムフィールドに値を登録する方法です。
今回は、カスタムフィールドに住所の値を登録すると緯度経度の情報をカスタムフィールドに登録するようなものを作成します。
WordPressのカスタムフィールドの住所から緯度経度を登録するためには、
- WordPressのカスタムフィールドから住所を取得
- 取得した値(住所)からカスタムフィールドに登録
- WordPressのカスタムフィールドに登録
と、いうような流れになります。
WordPressのカスタムフィールドから住所を取得
WordPressのカスタムフィールドから住所を取得する方法です。
今回は、保存した際に自動的に緯度経度を登録していきたいので、保存のタイミングでカスタムフィールドから値を取得します。
WordPressのタイミングとして、フックというものがあります。このフックに引っ掛けて関数を動作させます。
今回の候補のフックとして、『edit_post』『save_post』『wp_insert_post』がありますが、住所のカスタムフィールドの登録後が今回の動作タイミングなので、『wp_insert_post』を使用します。
function replace_post_address($id) {
$post = get_post($id);
// post_typeを判定(post, page, カスタム投稿)
if( $post->post_type == 'post' ){
$custom_fields = get_post_custom($id);
$custom_field_address = $custom_fields['address'];
// print_r($custom_field_address);
}
}
add_action( 'wp_insert_post', 'replace_post_address' );
と、するとカスタムフィールド(address)が取得出来ます。
取得した値(住所)からカスタムフィールドに登録
緯度経度情報を取得するにはGoolgeのAPIを利用します。
使用方法は非常に簡単で、『http://maps.google.com/maps/api/geocode/json?sensor=false&address=住所』で使用します。
返り値はJSONで取得します。
緯度経度情報登録
後は、取得した住所を変換し、カスタムフィールドに登録すれば完成です。
function replace_post_address($id) {
$post = get_post($id);
// post_typeを判定(post, page, カスタム投稿)
if( $post->post_type == 'post' ){
$custom_fields = get_post_custom($id);
$custom_field_address = $custom_fields['address'];
$data = @file_get_contents('http://maps.google.com/maps/api/geocode/json?sensor=false&address='.urlencode($custom_field_address[0]));
// カスタムフィールド(_lat)がセットされているか
if (isset($custom_fields['_lat'][0])) {
update_post_meta($id, '_lat', $data->results[0]->geometry->viewport->northeast->lat);
} else {
add_post_meta($id, '_lat', $data->results[0]->geometry->viewport->northeast->lat, true);
}
if (isset($custom_fields['_lng'][0])) {
update_post_meta($id, '_lng', $data->results[0]->geometry->viewport->northeast->lng);
} else {
add_post_meta($id, '_lng', $data->results[0]->geometry->viewport->northeast->lng, true);
}
}
}
add_action( 'wp_insert_post', 'replace_post_address' );
とすれば、登録出来ます。
セキュリティ面などは適宜変えて下さい。

![WordPressで新規投稿時に、別なカスタム投稿も追加する方法sand a lot | sand a lot Web & Music Create [札幌]](https://com4tis.net/_c4press/wp-content/uploads/2013/02/fba519c21aa6e278c06b324be17f5ef6-200x150.png)