Support » Plugins and Hacks » wp_insert_post memory problems

  • I’m writing a plugin which adds a whole bunch of pages to WP. My problem is memory use. Here’s an extract of the code:

    echo "D: ".(memory_get_usage() - $old_memory)."";
    $page_id = wp_insert_post($wm_mypost);
    echo "E: ".(memory_get_usage() - $old_memory)."";

    This outputs:

    D: 71652
    E: 1898444

    I could live with this memory use, but I’m in a loop so every time I call wp_insert_post my memory usage jumps by about 1Mb or so! (The loop calls a function, and wp_insert_post is inside the function. The memory is not reclaimed even when exiting the function.)

    So, what can I do to reclaim this memory?

Viewing 2 replies - 1 through 2 (of 2 total)
  • To aid further, I can see that most of the memory use is taken up within the rewrite_rules function which gets called every time you edit a post. So it seems as though there might be two possible solutions: (1) Fix rewrite_rules so it doesn’t eat my memory. Or (2) Add some kind of hook that temporarily prevents rewrite_rules from running when I add a page, then run it myself at then end. Haven’t a clue how do to either, though 😉

    OK, I solved my own problem. Here’s what I did.

    Firstly, I copied the _save_post_hook function and removed the rewrite commands from it.

    function sb_save_post_hook($post_id, $post) {
      if ( $post->post_type == 'page' ) {
        if ( !empty($post->page_template) )
          if ( ! update_post_meta($post_id, '_wp_page_template',  $post->page_template))
          add_post_meta($post_id, '_wp_page_template',  $post->page_template, true);
          //global $wp_rewrite;
      } else {

    Then I modified my code to change the actions when a post is saved. It now calls my custom function instead of the standard one. Then, outside the loop, I flushed the rewrite rules.

    remove_action('save_post', '_save_post_hook', 5, 2);
    add_action('save_post', 'sb_save_post_hook', 5, 2);
    foreach ($thing) {
    	$page_id = wp_insert_post($thing);
    remove_action('save_post', 'sb_save_post_hook', 5, 2);
    add_action('save_post', '_save_post_hook', 5, 2);
    global $wp_rewrite;
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_insert_post memory problems’ is closed to new replies.