我有一个包含车辆信息的sql表。当我将数据库表导入WordPress网站时,我需要将信息作为自定义帖子类型的自定义字段导入。例如,我创建了车辆自定义帖子类型和自定义字段:
add_action( \'init\', \'create_post_type\' );
function create_post_type() {
register_post_type( \'vehicle\',
array(
\'labels\' => array(
\'name\' => __( \'Vehicles\' ),
\'singular_name\' => __( \'Vehicle\' )
),
\'public\' => true,
\'has_archive\' => true,
)
);
}
add_action("admin_init", "admin_init");
function admin_init() {
add_meta_box("vehicle_info-meta", "vehicle Information", "vehicle_info", "vehicle", "normal", "low");
}
function vehicle_info() {
global $post;
$custom = get_post_custom($post->ID);
$stockNumber = $custom["stockNumber"][0];
$vin = $custom["vin"][0];
$make = $custom["make"][0];
?>
<p><label>Stock Number:</label>
<input name="stockNumber" value="<?php echo $stockNumber; ?>" /></p>
<p><label>Vin Number:</label>
<input name="vin" value="<?php echo $vin; ?>" /></p>
<p><label>Make</label>
<input name="make" value="<?php echo $make; ?>" /></p>
<?php
}
add_action(\'save_post\', \'save_details\');
function save_details() {
global $post;
update_post_meta($post->ID, "stockNumber", $_POST["stockNumber"]);
update_post_meta($post->ID, "vin", $_POST["vin"]);
update_post_meta($post->ID, "make", $_POST["make"]);
}
现在已经创建了自定义帖子类型,当我导入数据库表时,我需要为数据库表中的每辆车创建一个新的车辆帖子。我还需要填充每辆车的自定义字段。
SO网友:Shazzad
//将外部表导入WordPress的方法有点混乱。如果以某种方式将外部表数据解析为PHP变量ex:$data,那么导入就很简单了。
foreach( $data as $_dt )
{
$new_id = wp_insert_post( array(
\'post_type\' => \'vehicle\',
\'post_status\' => \'publish\',
\'post_title\' => $_dt[\'vehicle_name\']
));
if( !is_wp_error($new_id) )
{
update_post_meta($new_id, "stockNumber", $_dt["stockNumber"]);
update_post_meta($new_id, "vin", $_dt["vin"]);
update_post_meta($new_id, "make", $_dt["make"]);
}
}
//现在关于数据源,如果已经将自定义表导入WordPress数据库,请使用以下简单代码从中获取数据-
$data = $wpdb->get_results("SELECT * FROM $your_table_name");