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!

Filed under: Hacking, Programming

280 thoughts on “WordPress Post Inserts Are Super Slow

  1. Kermit says:

    I’m afraid that number’s ex-directory rshpharm.ecvery.com It follows growing evidence that children who form “secure attachments” in the first two years of their life are less likely to fail at school, become involved in crime and ultimately fail in their own relationships.

  2. Benedict says:

    I’m in a band bystrictin SYDNEY, Sept 24 (Reuters) – Asian share markets were mostlyunder water on Tuesday while currencies dithered in tight rangesas a dearth of major economic news left investors to fret on theoutlook for monetary policy in the United States and Europe.

  3. Gabriella says:

    What do you study? brookes pharma contact number A physically imposing presence with a booming voice, his motivational efforts were the stuff of legend: a clip of a semi-hysterical Ballmer screeching and dancing around the stage to rally Microsoft employees has been viewed nearly five million times on YouTube.

  4. Benjamin says:

    We’ll need to take up references jupiter medical center billing phone number Expansion teams in Arizona and Tampa Bay started play in 1998, raising the major league total to 30. Interleague play began in 1997 along with revenue sharing, which allowed the smaller-market clubs a better chance to compete. Jackie Robinson’s No. 42 was retired by Selig for all of MLB that same year, and other initiatives followed. Major League Baseball Advanced Media launched in 2000, the World Baseball Classic in 2006, limited video review of umpires’ calls in 2008 and the Major League Baseball Network in 2009.

  5. Malcolm says:

    I’d like to cancel a cheque bayonne pharmacy broadway bayonne nj 07002 “It’s like having an instrument,” she said. “You play the piano pretty well or you play a flute, you play the trombone, then all of a sudden you put it in a corner, cause you go, ‘I’m not going to do that anymore, I can’t, I don’t have time to do that,’ which is what I did, that’s your acting instrument.”

  6. Zoe says:

    Sorry, you must have the wrong number twinlab ripped fuel The war in Syria has driven 2.1 million refugees to seekshelter in neighbouring countries, according to the UnitedNations which predicts another million will join them by the endof the year and a further 2 million next year.

  7. Joaquin says:

    Incorrect PIN serpina7 Count Brooklyn Councilman Brad Lander and Manhattan Councilwoman Margaret Chin as brave for attempting to address the unnecessary use every year of more than 9 billion landfill-clogging, tree-decorating plastic bags.

  8. Abigail says:

    I’ll put her on cialis online legal bestellen Regulators said the next set of Fed-administered stress tests will start this fall. The 18 firms that participated in 2013, plus 12 additional banks with more than $50 billion in assets, will be included, the Fed said.

  9. Israel says:

    Sorry, I’m busy at the moment cialis 20mg lilly icos Telefonica, together with Italian investors Generali, IntesaSanpaolo and Mediobanca, controls Telecom Italia’s 14-strongboard via a holding company, Telco, which has a stake of onlyabout 22 percent in the group.

  10. James says:

    Gloomy tales rizatriptan odt 10 mg coupon “She had strong ideas about what I should do with the opportunities I had been given. I realised that as much as I tried not to care about the things my parents cared about, I did care about them,” she said. “Which was frustrating, in some ways. My grandmother, in her wizened way, just said, ‘Yes, I’ve been waiting for you to come to this realisation.'”

  11. Natalie says:

    It’s serious olympia pharmacy in orlando Traditional wisdom dictates that investing in commodities is supposed to act as a portfolio “hedge” and reduce overall volatility. However, the report by the Bank for International Settlements (BIS) released last week suggests commodities do not actually diversify investments at all.

  12. Grace says:

    Will I have to work on Saturdays? where to order orlistat The trust, a type known as a voluntary employees’beneficiary association or VEBA, is unhappy with the price Fiathas offered for its Chrysler stake. Now, the VEBA is exercisingits right to push Marchionne to take Chrysler public.

  13. Leslie says:

    I hate shopping cosmedica pure hyaluronic acid serum review “Some in our community believe that marijuana grow operations are run by compassionate caregivers interested only in supplying medicine to the sick,” said U.S. Attorney Melinda Haag in a statement Monday. “Unfortunately, this case illustrates what we in law enforcement see — marijuana grow operations that include heavily armed, violent individuals, motivated by profit, carrying out abuses of vulnerable victims.”

  14. Leland says:

    I’m a housewife cialis 20 mg precio espaa Jack had been scheduled to present his research on heart devices at Black Hat on August 1. Last week, Jack told Reuters he had devised a way to hack into a wireless communications system that linked implanted pacemakers and defibrillators with bedside monitors that gather information about their operations.

  15. Antonio says:

    Incorrect PIN brightoneggertpharmacy.com Prirazlomnaya, Russia’s first offshore oil rig in theArctic, is slated to start operating by the end of the year andis expected to reach peak production of 6 million tonnes peryear (120,000 barrels per day) in 2019.

  16. Dillon says:

    I’ve got a part-time job adaptogens for anxiety and depression “While it is hardly surprising that Mr. Trump would seek to stall the process and use the courts to repeat his ridiculous claims, Attorney General Schneiderman is focused on one thing only: pursuing justice for the people victimized by Mr. Trump and his scam university,” the spokesman said.

  17. Virgilio says:

    Is this a temporary or permanent position? adcirca emea When Rainwater arrived in London to play a series of television and concert dates, including an appearance on Sunday Night at the London Palladium, the airline mislaid his band parts. “It was the best thing that could have happened,” he noted, “because I ain’t suited to 40-piece orchestras.” Instead Johnny Duncan and his Blue Grass Boys provided the backing.

  18. Cooler111 says:

    I’m afraid that number’s ex-directory furosemide 20 mg side effects in elderly (The victims tended to win later on, getting advanced academic degrees while their former tormentors were relegated to out-shouting other parents at hockey games.) Remarkably, Johnson feels Jackie has no right to anonymity after she was attacked — and yet he now feels targeted, according to the Post, for attempting to unmask her

  19. Randell says:

    I’ve got a part-time job vitrix vs animal stak (Medical Xpress)—Low doses of a psychedelic drug erased the conditioned fear response in mice, suggesting that the agent may be a treatment for post-traumatic stress disorder and related conditions, a new …

  20. Lindsay says:

    Another service? accutane experience yahoo
    Asked about the incident during his All-Star news conference on Monday, Collins said, “He wasn’t happy. When he left the office, he was angry. The easiest way to put it is: I went out to the clubhouse to calm him down. It was not accepted very well by the other 24 guys, I can tell you that, too. We all know he’s an emotional kid. That’s how he plays and that’s how he goes about things.

  21. Tilburg says:

    I’m sorry, I didn’t catch your name green2go breakfast Leo Strine, the chief judge or chancellor on the Delaware Court of Chancery, said in his 24-page opinion that Liberty Media is entitled to the deal it struck in 2009. He also said the deal was fully disclosed and shareholders waited too long to sue.

  22. Ahmad says:

    I’d like to pay this cheque in, please methocarbamol webmd
    Meanwhile, at least 10 staff members were suspended last year for distributing pornographic images using the airline’s computers at Sydney Airport. There is no suggestion that a Qantas worker was responsible for the image that appeared on Facebook last week.

  23. Stephanie says:

    i’m fine good work benicar equivalent “I’d love to just fly home and switch off for a few months but the opportunities to compete in a world championship which suits climbers don’t come around very often so I think I’ve got to make the most of that,” he said.

  24. Winford says:

    Could I order a new chequebook, please? slimming tablets orlistat The dollar fell 0.2 percent against a basket of currencies, having touched an eight-month low of 79.627, on viewsthat the shutdown diminishes the chances of the Federal Reservereducing monetary stimulus this year. The euro firmed 0.3percent to $1.3619.

  25. Jospeh says:

    A few months cafepharma sanofi board In the face of opposition from the City Council, Filner could establish a legal defense fund and raise donations to pay for his own attorney, Erie said, though he added: “The question is how much and how many and whether they want their names to be made public.”

  26. Byron says:

    What qualifications have you got? generic allopurinol 100mg Our Classified websites (Photos, Motors, Jobs and Property Today) use cookies to ensure you get the correct local newspaper branding and content when you visit them

  27. Santiago says:

    Where did you go to university? terraillon kitchen scales manual But now the Government proposes to go back to the situation under existing legislation, which defines controlled expenditure as spending “which can reasonably be regarded as intended to promote or procure electoral success”.

  28. Walton says:

    What sort of music do you like? pharmacie-mans.com California Assembly Member Cristina Garcia, who was a moving force in the recall group called Basta said, “Closing this chapter validates the residents’ efforts in Bell. It reminds us that an informed and involved public can take their government back and that justice can be served.”

  29. Alfonso says:

    Where do you come from? imitrex heartburn
    Michelle Knight (2nd from left) reads statements while supported by her attorney (L) and friend as her accused assailant Ariel Castro (R) sits in the courtroom during Castros sentencing of kidnapping, rape and murder in Cleveland, Ohio August 1, 2013.

  30. Bryce says:

    Sorry, I ran out of credit pharmmarketconsulting.com The State Department travel alert was based on the same intelligence that prompted it to close 21 U.S. embassies and consulates on Sunday, August 4, chiefly those in the Muslim world, a U.S. official told Reuters on condition of anonymity.

  31. Adam says:

    Do you play any instruments? rogaine foam discount Organizers gave tips beforehand to anyone who was planning to be intentionally arrested.

  32. Faith says:

    Could I order a new chequebook, please? zovirax ma do oczu cena Whether changing his name from the apparently too bland Ron Artest, honoring Michael Jackson’s “Thriller” by giving himself jersey No. 37 (the number of weeks Jacko’s smash album topped the charts), asking his coach for time off because he was fatigued from promoting a rap album or, most famously, being a main combatant in an ugly brawl with opposing fans, the ex-St. John’s star from Queensbridge has generated plenty of headlines, many of them humorous.

  33. Johnathan says:

    I need to charge up my phone can i buy clomid over the counter in uk But Hansman said it seemed unlikely that the unit had malfunctioned, and that it was at least as likely that a passenger sneaked a cigarette in the lavatory and it smoldered for hours while the plane was parked at a remote stand at Heathrow airport before bursting into flames.

  34. Arron says:

    Do you know what extension he’s on? mf super scrub bodysuits
    SAN FRANCISCO — When the mayor of Richmond, Calif., and a gaggle of activists and homeowners showed up at the Wells Fargo Bank headquarters in downtown San Francisco this month, they were on a mission to speak with the bank’s chief executive.

  35. Ambrose says:

    Get a job conchitalorilyn.com “I do feel good about our chances. Post-Talladega, depending on how things play out there, we’ll see where we stand,” said Johnson when asked to assess his shot at a sixth Cup. “I know if we keep this pace up, we’ll definitely be a contender come Homestead. The big question is just Talladega.”

  36. Micheal says:

    Would you like to leave a message? periactin bodybuilding Sir James added: “We do need to keep certain people here, who come to our universities

  37. Mauro says:

    Best Site good looking humana pharmacy solutions Washington wants Snowden, who was in hiding in Hong Kong before flying to Moscow in June, to be sent home to face criminal charges including espionage for disclosing secret American internet and telephone surveillance programs.

  38. Antonio says:

    Have you read any good books lately? citalopram hydrobromide cost uk The source believes that “Andrew didn’t give a s— they were having an affair as long as he could hang out with Simon and play on his yacht. But now that it came out like this, it’s different. … It is no secret that she disdained [Andrew].”

  39. Judson says:

    How much were you paid in your last job? cheap purchase online naturally huge “I’m happily married to a wonderful man and fall in love with him more and more each day, and we’ll have a baby when god wants us to and when the time is right. These blatant lies are distasteful and shameless.”

  40. Cyril says:

    I live here pulmicort dose medscape
    For Evelyn Loux, Katlin’s death is the result of what she describes as incessant bullying from her daughter’s circle of once-friends and the failure of Parkway High School administrators here to stop the attacks.

  41. Aaliyah says:

    I’m in my first year at university zurvita amazon Some states that operate their own exchanges plan to identify marketplace-certified brokers, but that has not yet happened in all states, leaving a temporary gap for consumers. More than 2,600 state-licensed brokers cleared to work on New York’s exchange were expected to be listed on its website soon, the state’s health department said.

  42. Kurtis says:

    A book of First Class stamps kroger pharmacy the woodlands alden bridge This year is also the 110th anniversary of the first Tour de France race in 1903, and the 100th actual running of this most renowned of all bicycle competitions. We will have a daily peloton of cyclists riding period racing bikes, joined on track by a suitably French cavalcade of support vehicles, period promotional vans and much more. There may even be the odd familiar rider pedalling hard as well.

  43. Payton says:

    Can I call you back? cialis uk paypal It seems that Ms Karimova-Tillyaeva is not just distancing herself from her sister, but from the image of her country which is regularly portrayed as one of the worst dictatorships by human rights organisations.

  44. Wiley says:

    i’m fine good work costco pharmacy heartworm Despite the apparent policy shifts, Mexican officials continue to emphasize the need to attack the social causes of violence and to focus on reducing assaults, kidnappings, extortion and other crimes affecting most ordinary citizens.

  45. Ulysses says:

    Are you a student? levitra rezeptfrei paypal While most consumers will receive these updates — which may come as often as monthly — automatically via Windows Update, the mechanism already used to deliver security patches, businesses will be leery of such a quick cadence

  46. Tommy says:

    Looking for work low dose anadrol-50 When Schneider, who worked in the governor’s mansion from 2010 to early 2012, was confronted in early 2012 with charges that he had taken food from the governor’s mansion to support his own catering service, he met with federal authorities and investigators from the attorney general’s office and told them about Williams’ relationship with the governor.

  47. Raymond says:

    A company car sava medica limited review For now, production at Long Lake accounts for just over onetenth of Nexen’s overall production. CNOOC says it is seeking”new technology” to overcome the complex geology. It is not yetclear, industry analysts say, where that technology will comefrom.

  48. Mickey says:

    Where are you calling from? is robaxin an nsaid Johnbon, 29, im a frOe agent after t=& Jets dec,rned him option foo 2015 l{bt m|nsh

  49. Brianna says:

    I hate shopping androgel generic Heather (The Heat) Hardy ran her 5K for Sandy Saturday morning, and kept right on running, to her gym. She would very much like to have some stability, to not be without a home, for a bit. The toughest little mother in Brooklyn has found her way, her overarching goal not only to win a world championship, but to teach Annie a very important lesson.

  50. Ellis says:

    A staff restaurant cost of prostaglandin e1 But the National Multiple Sclerosis Society of the US says on its website: “In spite of long-standing claims about the possible benefits of bee venom for people with MS, a 24-week randomised study showed no reduction in disease activity, disability, or fatigue, and no improvement in quality of life.”

Leave a Reply

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