Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/1-generating-a-record.php Secret
Last active Aug 29, 2015

Embed
What would you like to do?
[WordPress] How to remove extraneous characters from the end of a line before preparing to write it to a file.
<?php
/**
* Note that in a production environment, much of this could would
* reside in several separate functions. It's shown here in one gist
* to illustrate the point more succinctly.
*/
/**
* Setup the WP Query arguments to retrieve all published
* posts of the 'acme_post_type' sorted by ascending
* title.
*/
$args = array(
'post_type' => 'acme_post_type',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'asc',
'posts_per_page' => -1
);
$custom_posts = new WP_Query( $args );
/**
* If there are posts, then loop through them creating
* a line to add to the CSV to write to the file.
*/
$csv_line = '';
if ( $custom_posts->have_posts() ) {
while ( $custom_posts->have_posts() ) {
$custom_posts->the_post();
// Grab the post title and a piece of associated meta data
$title = get_the_title();
$meta_data = get_post_meta( get_the_ID(), 'acme_meta_data', true );
// Append the content to the line to be written to the file
$csv_line = '"' . $title . '","' . $meta_data . '","' . "\"\r\n";
// Assume that we already have a file handle for writing the file
fwrite( $file_handle, $csv_line );
}
}
<?php
while ( $custom_posts->have_posts() ) {
/* Snip for redundancy */
// Append the content to the line to be written to the file
$csv_line = '"' . $title . '","' . $meta_data . '","' . "\"\r\n";
// Replace any "", with , and replace any trailing "" with an empty space
$csv_line = str_ireplace( ',""', '', str_ireplace( '"",', ',', $csv_line ) );
// Assume that we already have a file handle for writing the file
fwrite( $file_handle, $csv_line );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.