Updated: August 27th, 2012

Today's snippet is tremendously helpful if you are using an XML-RPC WordPress interface to read and publish your articles and are running into 500 Server Error issues due to running out of memory, manifesting themselves in something like this error message: "Invalid Server Response – The response to the metaWeblog.newMediaObject method received from the weblog server was invalid".

For example, my regular PHP memory allocation is 32MB or so, but if I load up Windows Live Writer, my favorite publishing tool, and ask it to load 1000 of the latest blog posts, I will undoubtedly get a server error back.

One solution would be to increase the memory allocated to PHP to something higher, like 256MB, which is how I used to get around the issue. I say "get around" because it's not a good solution – if someone finds a page that uses a lot of memory on your site, they could easily kill not only your web server but the whole machine due to swap death. Keeping a lower memory limit allows you to run your web server, such as Apache, with more children, thus serving more requests without getting overloaded.

So, I've looked into the WordPress core and came up with what I think is a proper fix – dynamic memory limit tweaking when dealing with XML-RPC only. Here is the code – add it to your functions.php and you should be golden:

1
2
3
4
5
6
7
8
9
10
11
/**
* Dynamically increase allowed memory limit for XML-RPC only.
*
* @param array $methods
* @return array
*/
function my_xmlrpc_methods($methods) {
  ini_set('memory_limit', '256M');
  return $methods;
}
add_action('xmlrpc_methods', 'my_xmlrpc_methods');

The code is pretty self-explanatory: it hooks into a WordPress hook that fires only for XML-RPC requests and adjusts the memory limit on the fly. No more out of memory errors and I'm able to load 1000 posts in Windows Live Writer without problems. If you want to load more, and PHP still crashes, try to raise this limit, but be careful not to send the server into swap death spiral.

● ● ●
Artem Russakovskii is a San Francisco programmer and blogger. Follow Artem on Twitter (@ArtemR) or subscribe to the RSS feed.

In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.