1

I have a sql table that contains vehicle information. When I import the database table to my WordPress website, I need the information to be imported as custom fields for a custom post type. For example, I created the vehicle custom post type and the custom fields:

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"]);
}

Now that the custom post type is created, when I import my database table, I need a new vehicle post to be created for each vehicle in the database table. I also need the custom fields for each vehicle to be populated.

1 Answer 1

1

// There's a confusion in which method you are importing your external table into WordPress. If someway you have parsed you external table data into a PHP variable ex: $data, then it would be simple to import.

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"]);
    }
}

// Now regarding the data source, if you have already imported your custom table into your WordPress Database, use this simple code to grab the data from it -

$data = $wpdb->get_results("SELECT * FROM $your_table_name");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.