Hacking, Programming

WordPress Post Inserts Are Super Slow

Logging another one of my “weird wordpress problems” here.

We use a plugin called Buddypress Private Checklist to offer wedding to-do lists to our members on the Offbeat Bride Tribe. It was written many years ago by our old developer, and I’ve been vaguely maintaining it in our open source plugin repo on git. But it was a hack when it was written (old dev’s words, not mine!) and we’ve grown a lot over the years. It’s in need of a major upgrade, and the first item on my docket was the fact that it takes forever to load the initial default tasks into a to-do list.

The initial task loader takes a CSV full of default tasks and inserts them as posts into the Worpdress database. We have 124 tasks and it was taking five minutes. I expect a loop of 124 inserts to be a little slow, but five minutes is insane.

The posts, which are a custom post type, also use custom taxonomies to organize them. When I disabled the taxonomy inserts, done with wp_set_object_terms(), everything ran quickly. When I tried the plugin on a fresh install it ran quickly even with the taxonomy information. Disabling all plugins and going to the default theme didn’t change anything. I finally put together a test page that just looped through a bunch of post and taxonomy inserts, and watched it with Query Monitor.

After every new taxonomy term is inserted, wordpress runs wp_update_term_count(). On something the size of a personal blog this is not a big deal. On a community with 40,000 posts and 900 tags, this takes maybe half a second. Doing that 124 times takes forever. Thankfully there is a way to disable this excessive recounting, wp_defer_term_counting().

function insert_many_posts(){
  wp_defer_term_counting(true);
  $tasks = get_default_tasks(); 
  for ($tasks as $task){
     $post = array(
       'post_title' => $task[content],
       'post_author' => $current_user->ID,
       'post_content' => '',
       'post_type' => 'bpc_default_task',
       'post_status' => 'publish'
     );
     $task_id = wp_insert_post( $post );

     if ( $task[category] )
        //Make sure we're passing an int as the term so it isn't mistaken for a slug
        wp_set_object_terms( $task_id, array( intval( $category ) ), 'bpc_category' );
  }
}

Now the whole loop takes about 10 seconds. Hooray!

227 thoughts on “WordPress Post Inserts Are Super Slow”

  1. This is the job description idrugstore.live-promo.net Diagnosis is simple. MRIs are NOT needed. An experienced physical exam will find this easily. The doctor will palpate the knee and when he/she pushes on this bursa it will hurt and you will tell the doctor, “that’s it”.

  2. Enter your PIN progesterone ordonnance Judge Blackett said Sgt Nightingale had “made up a spurious defence which falsely impugned the character of a fellow soldier and caused a number of SAS soldiers to risk their own security in giving evidence.”

  3. Could you ask her to call me? elysium health basis review Surging interest rates – and all indications are they aren’t going back down – will likely give us the answer by testing the resilience of U.S. housing markets. Here are some key indicators housing experts will be keeping their eyes on:

  4. I’m training to be an engineer achat cialis en france sans ordonnance Adapting to the major changes in screen size, interface, and functional capabilities will be a major challenge for software developers. While gazing at Time Square through Glass, how will the device compute what information to display when viewing hundreds of touch points via geo-fencing, visual recognition and QR codes? While there has been much discussion regarding “The Internet of Things”, our software capabilities are nowhere near the benchmark required to provide such experiences for users.

  5. It’s serious dermallure serum amazon He will be back in Madrid, keeping half an eye on what happens in St Petersburg, where a manager whose reputation for making teams into anything but a one-man show continues his task of resurrecting Russia.

  6. Which university are you at? cheap lipitor online The worst day of violence in more than a year has left Egypt, the Arab world’s most populous nation, more divided than ever in its modern history, and added pressure on the military-led authorities to explain how they will restore democracy.

  7. Special Delivery thyroid t3 t4 While simpler feature phones still account for a bulk ofNokia’s handset shipments, smartphones are viewed as crucial forits survival because of their higher margins, increasing demandfor Internet access and consumers’ growing tendency to switch tocheaper models made by Asian manufacturers.

  8. How do you do? rx pharmacy glendale ny He loved the University of Michigan, his alma mater. Yes, he had plenty of stories about his days there, where he was a sports reporter on the student newspaper. When one of Michigan’s basketball stars, Cazzie Russell, signed with the Knickerbockers, Mazer was elated. He made Russell a regular on the show. Mazer made listeners feel Russell was part of the family.

  9. Best Site good looking cigna pharmacy telephone number “Clearly, something has killed a lot of people,” says Dan Kaszeta, a former U.S. Army chemical officer and Department of Homeland Security expert now a private consultant. “We’re not going to know what until someone gets a sample.”

  10. I’m in a band prilosec otc for horses
    We can’t get rid of the technology – nor would we want to. All of the social media sites have positive characteristics, be it reconnecting to a long-lost friend or helping to organize a grassroots revolution. And they have negative aspects, ranging from way too much oversharing about minutiae to actually threatening people. The fact that the technology exists is not the problem. It’s how a few haters are using it.

  11. On another call sawahpharma.com The movie is the story of the search for two girls who are kidnapped on Thanksgiving Day. One of their fathers, a Pennsylvania survivalist played by Jackman, grows frustrated with the police investigation and employs his own methods to find out what happened.

  12. I’m about to run out of credit isordil sublingual 5mg comprar Question with respect to your counter ’14 total revenue guidance of about 15% year-over-year. We forecasted the continued strength on ELA renewals is definitely going to continue throughout 2014 I think the new ELA signs will be strong as well. Can you talk a little bit about what that 15% overall revenue growth is predicated on with respect to transactional business because obviously that’s being moving in the wrong direction as off late. Thanks guys.

  13. Who’s calling? alldaychemist inbound into customs
    As painful as it is, I prefer to see the debt addressed now. Until both sides feel pain, there will be no deal, so let the pain begin now. Until it gets to the place where there is MEMORABLE pain for all the Government leadership, to the point that they will proactively keep us out of this and other growing debt situations, I hope there is no deal.

  14. Languages wo kann man acai berry kaufen “It was raw, it was real, it was not cheesy,” he says. “It was so real, the malady of love that these men were singing about. Their hearts broken, singing about that…I mean, have a glass of wine and listen to one of those old records. It’s mind blowing!”

  15. I’ll put her on para que es el lexapro Ising hosted two members of another white supremacist group, the Aryan Terror Brigade, at his home in Wareton on December 31, 2011, where they drank alcohol, listened to white supremacist music and plotted attacks on random non-white victims, prosecutors said.

  16. I’m not sure pennington pharmacy pennington gap va It’s no ordinary day for Vanessa Carlton. The 29-year-old singer-songwriter came out at the Nashville Pride Festival over Father’s Day weekend to a crowd of 18,000, the Huffington Post reports. ‘I’ve never said this before, but I am a proud bisexual woman,’ she told the audience as she hit the stage on June 19.

  17. Please wait healthpharmacy.info The homemade time bomb that went off just before midnight Monday at the Traders Hotel was hidden in the bathroom in an American family’s room on the ninth floor. There was no indication they had been targeted.

  18. Some First Class stamps snafi tablets in uk
    GE has been one of the relatively small number of majorforeign investors in Italy since 1994 when it acquired NuovoPignone, a specialist in machinery for the oil and gas industry.Last year, it bought the aviation unit of Italian aerospacesupplier Avio for $4.3 billion.

  19. I’m sorry, he’s high t womens cost On a night he allowed only two hits and three baserunners in eight innings, Verlander made it a postseason-record 30 straight scoreless innings against one team since Coco Crisp hit a leadoff home run for the A’s in Game 1 last October.

  20. The United States pavilions pharmacy monrovia ca “The operation went very well,” Alfredo Scoccimarro, her spokesman, told well-wishers outside the Favaloro Foundation clinic in Buenos Aires. “The president is in her room. She is in very good spirits. She said hello to everyone.”

  21. I’ll send you a text herbal ignite canada
    The Chiefs haven’t returned a punt for a touchdown since McCluster took one back against the Chargers in September 2010. The last time they brought back a kickoff for a touchdown was November 2011, when Pro Bowl running back Jamaal Charles was still forging his name in the league.

  22. What line of work are you in? buy cheap tamoxifen “You can’t get these guys on boards to be accountable, unless you have a lot of capital anda lot of firepower,” Icahn said. “You get one or two of your candidates on the boards. That’show it’s done.”

  23. Could I make an appointment to see ? port allegany pharmacy
    The United States, France and Britain want a council resolution issued under Chapter 7 of the U.N. charter, which could authorize sanctions or military intervention if Damascus reneges on its commitments.

  24. perfect design thanks mobic medscape
    It’s subtle and elegant, unlike most of the menu. Rosen seems to be striving for a midtown Sarabeth’s. But Enduro’s renditions of aw-shucks staples and toothless ethnic dishes recall a different Manhattan classic — the dingy diner where coffee and a muffin was your safest bet.

  25. I’d like to pay this in, please acyclovir online australia
    Lakin is making coffins for people years before they die but with a twist – he makes them as furniture pieces that can be displayed in their homes until they are needed. Lakin lectures on affordable furniture alternatives, and over the last five years has developed a line of coffins that serve as functional pieces of furniture. The furniture pieces are easily converted to coffins.

  26. Special Delivery omeprazole prices uk Facebook and Twitter were blocked by Beijing in mid-2009following deadly riots in the western province of Xinjiang thatauthorities say were abetted by the social networking sites. TheNew York Times has been blocked since reporting last year thatthe family of then-Premier Wen Jiabao had amassed a hugefortune.

  27. I’m sorry, he’s growth factor 9 uk reviews Should current trends continue, U.S. combat troops are likely to leave behind a grinding stalemate between the Afghan government and the Taliban. The Afghan National Security Forces can probably sustain this deadlock, but only as long as the U.S. Congress pays the multibillion-dollar annual bills needed to keep them fighting. The war will thus become a contest in stamina between Congress and the Taliban. Unless Congress proves more patient than the Taliban leader Mullah Omar, funding for the ANSF will eventually shrink until Afghan forces can no longer hold their ground, and at that point, the country could easily descend into chaos. If it does, the war will be lost and U.S. aims forfeited. A policy of simply handing off an ongoing war to an Afghan government that cannot afford the troops needed to win it is thus not a strategy for a “responsible end” to the conflict; it is closer to what the Nixon administration was willing to accept in the final stages of the Vietnam War, a “decent interval” between the United States’ withdrawal and the eventual defeat of its local ally.

  28. A staff restaurant anabolic-performance.com reviews
    Market volatility could rise if the deadlock continues asconcern about the economic impact mounts. Goldman Sachsestimated a short-term shutdown would slow U.S. economic growthby about 0.2 percentage point, while a weeks-long disruptioncould weigh more heavily – 0.4 percentage point – as furloughedworkers scale back personal spending.

  29. How long have you lived here? billig kamagra oral jelly While Canelo has demonstrated punching power, it’s one thing blowing away physically overmatched opponents such as Alfonso Gomez, Kermit Cintron and Josesito Lopez and another matter altogether trying to bring firepower to bear on a boxer of Mayweather’s prowess.

  30. A staff restaurant drug-shop.com The salon uses a team of five one-year-old Japanese native snails. And when they're not crawling about on a customer's face, they dine on high-grade vegetables to help keep them in shape. Some beauty experts dispute claims they can help reinvigorate the skin.

  31. I enjoy travelling rx.com reviews
    Wall Street is a partner with industry in spreading thecosts and risks of commodities investments, the letter said, andif the Fed were to drive banks from the market “we likely wouldbe forced to tie-up our own capital in holding physicalinventories and the related infrastructure to manage thoseinventories.”

  32. Do you know each other? deltasone pharmacy2us
    Cybersecurity experts warn that relentless efforts to hack into U.S. banks and financial institutions, the power grid and other critical infrastructure, paired with instances of disruptive attacks abroad, pose a national security threat.

  33. Can I call you back? minoxidil 5 prix belgique “I think our style of play is if you don’t work hard, don’t win battles, you’re not going to win games,’’ he said. “That was the problem the first few games. We were getting outmuscled, outworked. When you wear the Flyers crest, you have to be a hard-nosed, hitting, playing-hard team.’’

  34. Can you hear me OK? qu’est ce que le tadalista He’s right, but the Jets’ ability to keep Tom Brady from converting a third down for the first 52 minutes or hold a 23-minute time-of-possession advantage over the Patriots will be lost amid the controversy surrounding a new rule that, frankly, the NFL’s official website didn’t even understand.

  35. Can I use your phone? vikonon warning Obama had been strongly leaning toward picking Summers, who helped him navigate the depths of the financial crisis and recession at the beginning of his term, and had assurances from Democratic Senate leadership leaders that they would work to get him confirmed, according to people familiar with the matter.

  36. Could you tell me my balance, please? pilocarpine webmd
    “Fonterra is our largest exporter and they’re completely intertwined with New Zealand’s image and also they’re the absolute biggest benefactor of the ‘100% Pure’ brand. When you’re coming out with something that presents itself as fact, or 100% pure, then you have to be 100% pure and we’ve proven that we’re not.”

Leave a Reply

Your email address will not be published. Required fields are marked *