After the call of wp_update_post($my_post) I checked memory_get_usage(). With every call in a post update inside a foreach loop the memory usage is getting higher and higher.
Here are the outputs from echo memory_get_usage(); which I did after wp_update_post():
1st call= 72923956
2nd call= 89410604
3rd call= 105152440
4th call= 120900116
5th call= 136651592
6th call= 152432716
7th call= 168178896
and then…
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 15728640 bytes) in …/wp-includes/wp-db.php on line 1196
My question is:
Is there a possibility of flushing the memory, delete the content of the $my_post arrays which I built for wp_update_post()? By the way: The size of the arrays are appx 1000 characters each…
Here is a generalized code. You can search for “wp_update_post” to find the line with the memory problem.
Thanx for helping,
Mat
<?
function event_sync_doit() {
$limit = $_POST['limit']; // 1-1500
$start = $_POST['start']; // 0-1500
$range = $_POST['range']; // 1-100
$end = min ( $start + $range , $limit );
$string = file_get_contents("https://www.example.com/party/api/json/?limit=".$limit);
$json=json_decode($string,true);
for ($i = $start; $i <= $end; $i++) {
$event_id = $json['partylist'][$i][id];
// ######### DELETED PART #########
// Here we have a lot of variable assignments
// ######### DELETED PART #########
if ( ($event_id>0) ) {
// READ XML FROM example.com API
$xml = simplexml_load_file('https://www.example.com/party/xml/'.$event_id); // or exit();
// ######### DELETED PART #########
// Here we have a lot of variable assignments
// ######### DELETED PART #########
// SET FLYER
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
$flyerfull_url = $xml->party[0]->{'flyerfull-url'};
$flyersmall_url = $xml->party[0]->{'flyersmall-url'};
$flyer_title = $start_date." - ".$partyname;
if ( ($post_thumbnail_id > 0) AND ($post_thumbnail_id != 14072)) {
// there is already a a standard post thumbnail with id 14072
} else if ($flyerfull_url != "") {
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($flyerfull_url);
$filename = basename($flyerfull_url);
if(wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $flyer_title,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
} else {
// set placeholder picture
set_post_thumbnail( $post_id, "14072" );
}
// WRITE CONTENT HTML
if ( intval($lat) > 0 AND intval($lon) > 0 ) {
$map_info = "<br><br><i>Scroll down for location map</i>";
}
else {
$map_info = "";
}
// ######### DELETED PART #########
$out = "COMPLETE STRING OF CONTENT - APPX 1000-2000 CHARACTERS EACH ENTRY";
// ######### DELETED PART #########
// -----------------
// LINK URLS
// -----------------
$out = preg_replace_callback(
'/((https?://)(www.)|(https?://)|(www.))([^</?s]+)[^<s]*/',
function ($matches) {
switch($matches[6]){
// ------------------------------------------------------------------------
case 'facebook.com':
$graph_url = str_replace("//www.","//graph.",url_trim($matches[0],"http://"));
$alter_error_handler = set_error_handler("mush_ErrorHandler");
$seite = file_get_contents($graph_url, false, $context);
restore_error_handler();
$graph = json_decode($seite, true);
if ($graph["id"] > 0 AND $graph["gender"] = "") {
$return = "<br>[dpSocialTimeline skin="light" total="2" items="{'name':'facebook_page','data':'".$graph["id"]."','limit':'20'}"Â showFilter="0" showLayout="0" itemWidth="47%"]<br>[su_spacer]";
}
else if ($graph["name"]) {
($graph["name"] == "") ? $fb = "" : $fb = " of ".$graph["name"];
$return = "<a href="" . url_trim($matches[0],"http://") . "">Facebook Profile". $fb ."</a><br>[su_spacer]";
}
else {
$return = "<a href="" . url_trim($matches[0],"http://") . "">Facebook Profile</a><br>[su_spacer]";
}
return $return;
// ------------------------------------------------------------------------
case 'soundcloud.com':
$alter_error_handler = set_error_handler("mush_ErrorHandler");
$seite = file_get_contents("http://api.soundcloud.com/resolve.json?url=".url_trim($matches[0],"http://")."&client_id=c16efb34d50753daa59a5b6e9ef7ab44", false, $context);
restore_error_handler();
$json = json_decode($seite, true);
return "<br>[iframe src="https://w.soundcloud.com/player/?url=https%3A//".url_trim($json['uri'],"")."&auto_play=false&hide_related=false&visual=true" width="100%" height="450"]<br>[su_spacer]";
// ------------------------------------------------------------------------
case 'example.com':
return "" . $matches[0] . "";
// ------------------------------------------------------------------------
default:
return "<a href="" . url_trim($matches[0],"http://") . "">".url_trim($matches[0],"")."</a>";
}
},
$out);
$out = str_replace("<br />","<br>",$out);
$out = str_replace("/>","",$out);
// --------------------
// GOOGLE MAPS
// --------------------
if ( intval($lat) > 0 AND intval($lon) > 0 ) {
$out = str_replace("{{LOCATIONMAP}}", "
<tr>
<td class='party_head'> Map </td>
<td class='party_info'> [su_gmap width='540' height='500' responsive='yes' address='". $lat . "," . $lon . "']</td>
</tr>
", $out);
} else {
$out = str_replace("{{LOCATIONMAP}}", "", $out);
}
// ------------------------------------------------------------------------
// <<< END CREATE CONTENT
// ------------------------------------------------------------------------
} else {
$wp_post = NULL;
echo "<p> No example ID found !!! </p>";
}
if ( $wp_post ) {
// Update Party entry
$my_post = array(
'ID' => $post_id,
'post_title' => $nameParty,
'post_status' => 'publish',
'post_content' => $out,
'post_author' => 2,
'post_category' => array(118)
);
// ------------------------------------------------------------------------
// Update the post into the database
echo memory_get_usage()."<br>";
print_r($my_post);
// ------------------------------------------------------------------------
wp_update_post( $my_post );
// ------------------------------------------------------------------------
echo memory_get_usage()."<br>";
$base_url = get_site_url();
// ------------------------------------------------------------------------
echo "<p> UPDATE PARTY ENTRY (<a href='$base_url?p=$post_id'>$post_id</a>) $sort_records <br>
<a href='http://www.example.com/$event_id' target='_blank'><b>$nameParty</b></a><br>
$sub_head </p>";
} else {
// Create post object
$my_post = array(
'post_name' => $event_id,
'post_title' => $nameParty,
'post_content' => $out,
'post_author' => 2,
'post_date' => $dateCreated,
'post_date_gmt' => $dateCreated,
'post_type' => 'post',
'post_status' => 'publish',
'post_category' => array(118)
);
// Insert the post into the database
$post_id = wp_insert_post($my_post);
// $post_id = mush_get_post_id_by_name($event_id);
echo "<p> CREATE PARTY ENTRY (<a href='$base_url?p=$post_id'>$post_id</a>) $sort_records <br>
<a href='http://www.example.com/$event_id' target='_blank'><b>$nameParty</b></a><br>
$sub_head </p>";
}
if ( $meta_event_id == $event_id OR $meta_event_id == "" OR $meta_event_id == NULL) {
delete_post_meta( $post_id, "event_id");
add_post_meta( $post_id, "event_id", $event_id );
delete_post_meta( $post_id, "sub_head");
add_post_meta( $post_id, "sub_head", $sub_head );
delete_post_meta( $post_id, "sort_records");
add_post_meta( $post_id, "sort_records", $sort_records );
if ( get_post_meta( $post_id, "geo_location", TRUE )) {
delete_post_meta( $post_id, "geo_location");
add_post_meta( $post_id, "geo_location", $geo_location );
}
} else {
return "example ID <> example META INFO. PLEASE CHECK ID ".$event_id." / META-ID ".$meta_event_id;
}
}
}
?>
I am not sure of the exact reason but you can try to unset
$xml
variable once the loaded file has been processed, similarly try removing large variables( file_get_contents returns ) when no longer in use. This could lower the memory requirement for eachfor
loop.