Reputation: 35
I have some code that I've written to pull attachments in my posts table of my wordpress site.
The first function pulls down the results, but I cannot get it to write to a text file.
Creation of the file is fine, and I get no errors. And the code is operating, I'm just not getting a log. I want to know what files it is prepping to move.
This is the function in question from my plugin
function getPostsToMove($baseurl){
$baseurl = $baseurl.'/%/%/%.%';
$myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");
global $wpdb ;
return $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not
like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");
fwrite($myfile, $baseurl);
fclose($myfile);
}
What am I missing?
EDIT- I had the order wrong. THose below were right. But apparently I'm not fetching the data from my return. Do I need to turn that into an array?
New code
function getPostsToMove($baseurl){
$baseurl = $baseurl.'/%/%/%.%';
$myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $output);
fclose($myfile);
global $wpdb;
$output = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not
like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");
return $output;
}
Upvotes: 1
Views: 2719
Reputation: 640
Your function appears to be retrieving the query AFTER attempting to write to the file.
As it looks like you are planning to retrieve the data, write it to a file, and then return the data for further use in your application, I would suggest something like below.
function getPostsToMove($baseurl){
$baseurl = $baseurl.'/%/%/%.%';
$myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");
// Query the data and assign the variable before writing
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");
// json_encode() to turn the retrieved array into a JSON string for writing to text file
$output = json_encode($results);
// write the file
fwrite($myfile, $output);
fclose($myfile);
// return the result (array) for further use in application
return $results
}
Upvotes: 2