-
-
Save tommcfarlin/dec9bc8eda937e5c9ab0 to your computer and use it in GitHub Desktop.
[WordPress] How to remove extraneous characters from the end of a line before preparing to write it to a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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