我在用数据库中的数据更新自定义字段(在自定义帖子类型中)时遇到了一个真正的问题。
数据库中有一个表名为wp_company_profiles
带有地址字段(即address\\u 1、address\\u 2)。我在admin post区域中为每个字段设置了具有相同值的自定义字段。我正试图创建一个钩子,从数据库中检索数据以更新自定义字段。
下面是代码,但我不知道它缺少什么。
function get_fields_company_profile($post_id) {
global $wpdb;
if ($parent_id = wp_is_post_revision( $post_id )) $postid = $parent_id;
$postid = $_GET[\'post\'];
$row = $wpdb->get_row( "SELECT * FROM wp_company_profiles WHERE pid = \'$postid\' " );
if ($row) {
// retrieve fields from database
$address1 = $row->address_1;
$address2 = $row->address_2;
$postcode = $row->postcode;
$city = $row->city;
// update custom fields in admin area
update_post_meta($post_id, \'address_1\', $address1);
update_post_meta($post_id, \'address_2\', $address2);
update_post_meta($post_id, \'postcode\', $postcode);
update_post_meta($post_id, \'city\', $city);
}
}
add_action(\'init\', \'get_fields_company_profile\');
最合适的回答,由SO网友:Shazzad 整理而成
首先,init hook不提供$post_id
作为论据。
其次,您缺少匹配的变量名-$postid
&;$post_id
这是修改后的代码-
function get_fields_company_profile()
{
if(
isset($_GET[\'post\']) && \'\' != $_GET[\'post\']
&& isset($_GET[\'action\']) && \'edit\' == $_GET[\'action\']
&& ( !isset($_GET[\'post_type\']) || \'post\' == $_GET[\'post_type\'] )
){
global $wpdb;
$postid = (int) $_GET[\'post\'];
$row = $wpdb->get_row( "SELECT * FROM wp_company_profiles WHERE pid = \'$postid\'" );
if ($row)
{
// retrieve fields from database
$address1 = $row->address_1;
$address2 = $row->address_2;
$postcode = $row->postcode;
$city = $row->city;
// update custom fields in admin area
update_post_meta($post_id, \'address_1\', $address1);
update_post_meta($post_id, \'address_2\', $address2);
update_post_meta($post_id, \'postcode\', $postcode);
update_post_meta($post_id, \'city\', $city);
}
}
}
add_action(\'load-post.php\', \'get_fields_company_profile\');