我有一个有点不正统(我猜)的问题。我有一个功能,可以添加记录到我的MYSQL数据库,具有位置lat和lng信息。但是,有时该功能无法正常工作,导致无法创建DB记录。因此,我想创建一个循环来继续检查函数是否创建了DB记录,如果没有,再次执行该函数。 只是为了清楚;我使用的函数是默认的GEOMyWP函数(reference)。有时它无法正常工作,我想由于Google Maps API的响应时间。
我的functions.php中有以下内容,它似乎正在运行。我真的很想知道这是否是实现上述目标的正确方法,因为我不确定。感谢
global $wpdb;
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
if ($myccount <= 0) :
while ($myccount <= 0) :
gmw_pt_update_location( $args ); //The function I would like to check.
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
endwhile;
endif;
以下是在为CPT创建帖子时用于导入地址的功能
function gmw_update_post_type_post_location( $post_id ) {
// Return if it's a post revision
if ( false !== wp_is_post_revision( $post_id ) )
return;
// check autosave //
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
//check if user can edit post
if ( !current_user_can( 'edit_post', $post_id ) )
return;
//Add post Meta
add_post_meta($post_id, 'address', $_POST['address'], false);
//get the address from the custom field "address"
$addressarray = get_post_meta( $post_id, 'address', true );
$address = $addressarray[0];
//$address = $_POST['address'];
//varify that address exists. Otherwise abort the function.
if ( empty( $address ) )
return;
//include the update location file file
include_once( GMW_PT_PATH .'/includes/gmw-pt-update-location.php' );
//make sure the file included and the function exists
if ( !function_exists( 'gmw_pt_update_location' ) )
return;
//Create the array that will pass to the function
$args = array(
'post_id' => $post_id, //Post Id of the post
'address' => $address // the address we pull from the custom field above
);
//Start counting 1
global $wpdb;
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
if ($myccount <= 0) :
while ($myccount <= 0) :
//Add location
gmw_pt_update_location( $args );
//Start counting 2
$myccount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."gmw_locations WHERE object_id = %d", $post_id));
endwhile;
endif;
}
//execute the function whenever post type is being updated
add_action( 'save_post_mpp-gallery', 'gmw_update_post_type_post_location', 13, 1 );
最终将记录插入数据库的函数是:gmw_update_location 此功能可以在GEOMyWP插件中找到。请参阅此链接以获取参考:https://github.com/Fitoussi/geo-my-wp/blob/master/includes/gmw-location-functions.php#LC194