Output Query into CSV from WordPress

I’ve created a query that pulls the values I want from the DB, and it is placing them into an array (the var_dump shows this) however no file is being created. This has been pieced together from a hodge-podge of sources to get this far. Somewhere I am missing something to actually create the CSV file and force the download.

function wpcp_export_inventory_feed()
{


$args = array(
    'showposts'        => -1,
'offset'           => 0,
'orderby'          => 'date',
'order'            => 'DESC',
'post_type'        => 'inventory',
'post_status'      => 'publish',
'suppress_filters' => true 
);

$posts = get_posts($args);

$fh = fopen( 'wp-content/uploads/export.csv', 'w');

$vehicles[] = array();
$vehicles[] = array('Stock', 'Year', 'Make', 'Model', 'Trim', 'Auto Title', 'VIN', 'Price', 'Discount', 'MSRP', 'Mileage', 'Body Style', 'Engine', 'Transmission', 'Exterior Color', 'Interior Color', 'Fuel', 'MPG City', 'MPG Hwy');

while ( have_posts() ) : the_post();

    $autoID = get_the_ID();
    $year = get_post_meta( $autoID, '_auto_year', true );
    $make = get_post_meta( $autoID, '_auto_make', true );
    $model = get_post_meta( $autoID, '_auto_model', true );
    $trim = get_post_meta( $autoID, '_auto_trim', true );
    $autotitle = "$year $make $model $trim" ;
    $autostock = get_post_meta( $autoID, '_auto_stock', true );
    $autovin = get_post_meta( $autoID, '_auto_vin', true );
    $autoprice = get_post_meta( $autoID, '_auto_price', true );
    $autodiscount = get_post_meta( $autoID, '_auto_discount', true );
    $automsrp = get_post_meta( $autoID, '_auto_msrp', true );
    $automileage = get_post_meta( $autoID, '_auto_mileage', true );
    $autobodystyle = get_post_meta( $autoID, '_auto_body', true );
    $autoengine = get_post_meta( $autoID, '_auto_engine', true );
    $autotrans = get_post_meta( $autoID, '_auto_trans', true );
    $autocolorext = get_post_meta( $autoID, '_auto_color_ext', true );
    $autocolorint = get_post_meta( $autoID, '_auto_color_int', true );
    $autofuel = get_post_meta( $autoID, '_auto_fuel', true );
    $autompgcity = get_post_meta( $autoID, '_auto_gasmiles_city', true );
    $autompghwy = get_post_meta( $autoID, '_auto_gasmiles_hwy', true );

    $vehicles[] = array($autostock, $year, $make, $model, $trim, $autotitle, $autovin, $autoprice, $autodiscount, $automsrp, $automileage, $autobodystyle, $autoengine, $autotrans, $autocolorext, $autocolorint, $autofuel, $autompgcity, $autompghwy);

endwhile;

foreach($vehicles AS $vehicle) { fputcsv($fh, $vehicle, ';'); }
fclose($fh);

var_dump($vehicles);

}

Related posts

1 comment

  1. I think you have a path issue. At least you would have a zero sized file if the rest of your logic had an issue. If you scan all your folders you will probably find it.

    You need to give the path a root anchor:

    $fh = fopen ('/wp-content/uploads/export.csv', 'w');
    

Comments are closed.