自定义字段不更新后保存WordPress


Custom Field Not Updating on Post Save WordPress

我已经编写了一个函数来接受一些自定义分类法& &;post title(在本例中为street (post title), city, state, zip),并将其地理编码为要保存到自定义字段_ct_latlng中的lat/long。

问题是它不触发后保存或更新。任何帮助都是感激的!

function ct_geocode_address($post_id) {
    global $post;
    if($_POST['post_type'] != 'listings')
        return;
    $city =  wp_get_post_terms($post_id, 'city');
    $city = $city[0];
    $city = $city->name;
    $state =  wp_get_post_terms($post_id, 'state');
    $state = $state[0];
    $state = $state->name;
    $zip =  wp_get_post_terms($post_id, 'zipcode');
    $zip = $zip[0];
    $zip = $zip->name;
    $street = get_the_title($post_id);
    if($street && $city) {
        global $post;
        $url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($street.' '.$city.', '.$state.' '.$zip)."&sensor=false";
        $resp = wp_remote_get($url);
        if ( 200 == $resp['response']['code'] ) {
            $body = $resp['body'];
            $data = json_decode($body);
            if($data->status=="OK"){
                $latitude = $data->results[0]->geometry->location->lat;
                $longitude = $data->results[0]->geometry->location->lng;
                print $latitude.','.$longitude;
                update_post_meta($post_id, "_ct_latlng", $latitude.','.$longitude);
            }
        }
    }
}
add_action('save_post', 'ct_geocode_address');

尝试替换

if($_POST['post_type'] != 'listings')

$post = get_post( $post_id );
if($post->post_type != 'listings')
更新:

问题是您正在以默认优先级10运行ct_geocode_address函数。

在主题的其他地方有代码更新手动输入到清单元框中的值。手动输入的值将覆盖通过ct_geocode_address()设置的值。这意味着该字段正在保存,但随后它会根据从edit.php发送的$_POST值再次保存。

改变
add_action('save_post', 'ct_geocode_address');

add_action('save_post', 'ct_geocode_address', 999);

自定义帖子类型slugs往往是单数-也许这只是一个打字错误?试着测试listing(单数)而不是listings(复数)。当然,这取决于您如何定义CPT。

另外,尝试使用get_post_type()函数来测试。

if( get_post_type( $post_id ) != 'listing' )

$lan = $latitude.','.$longitude;
update_post_meta($post_id, "_ct_latlng", $lan);