我试图从一个wordpress帖子插入数据到一个新的表数据库表,而不是WP_postmeta
。我的功能正在工作,它会插入$postid
,完全没有问题。我遇到的问题是我需要从Marty Spellerbergs 'Address Geocoder' Plugin插入纬度和经度坐标。
在插件页面上,可以在这里看到https://wordpress.org/plugins/address-geocoder/, Marty说你可以使用以下方式访问循环中的坐标:
<?php echo get_geocode_lng( $post->ID ); ?>
<?php echo get_geocode_lat( $post->ID ); ?>
现在我知道在函数。php文件中,我们实际上不在循环中,所以我尝试了很多不同的方法来访问这些数据,但我就是做不到。有没有办法编辑Marty指定的那些行,以便在函数中调用它们?
这是我无数次尝试中的一次:
function save_lat_lng( $post_id )
{
global $wpdb;
global $post;
$custom_lat = $_POST[get_geocode_lat( $post->ID )];
$custom_lng = $_POST[get_geocode_lng( $post->ID )];
// Check that we are editing the right post type
if ( 'festival-event' != $_POST['post_type'] )
{
return;
}
// Check if we have a lat/lng stored for this property already
$check_link = $wpdb->get_row("SELECT * FROM lat_lng_post WHERE post_id = '" . $post_id . "'");
if ($check_link != null)
{
// We already have a lat lng for this post. Update row
$wpdb->update(
'lat_lng_post',
array(
"lat" => $custom_lat,
"lng" => $custom_lng
),
array( 'post_id' => $post_id ),
array(
'%f',
'%f'
)
);
}
else
{
// We do not already have a lat lng for this post. Insert row
$wpdb->insert(
'lat_lng_post',
array(
'post_id' => $post_id,
"lat" => $custom_lat,
"lng" => $custom_lng
),
array(
'%d',
'%f',
'%f'
)
);
}
}
add_action( 'save_post', 'save_lat_lng' )
如果您将post_id
作为参数传递给函数save_lat_lng,我认为您应该更改这两行:
$custom_lat = $_POST[get_geocode_lat( $post->ID )];
$custom_lng = $_POST[get_geocode_lng( $post->ID )];
$custom_lat = get_geocode_lat( $post_id );
$custom_lng = get_geocode_lng( $post_id );
如果你想检查文章类型你应该修改
if ( 'festival-event' != $_POST['post_type'] )
if ( 'festival-event' != get_post_type($post_id) )
文档如下:https://codex.wordpress.org/Function_Reference/get_post_type
p。下次你应该粘贴插件链接,这样可以节省时间:)
,
坐标不可用-问题与save_post钩子优先级值有关。
从插件代码我看到功能更新后元有优先级:
add_action( 'save_post', array( $this, 'save_post' ), 10, 2 );
所以要在那之后运行钩子,你应该这样设置:
add_action( 'save_post', 'save_lat_lng', 100 );