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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. We’ll need to take up references winky lux lipstick mecca For all of 2009, Pimco’s Total Return Fund posted a return of 13.83 percent. It was thefund’s best showing in a decade, beating the Barclays U.S. Aggregate Bond Index by nearly eightpercentage points – its widest spread over the benchmark, according to Morningstar, since 1988,the fund’s first full year of operation. By far the biggest contributor – at 4.15 percentagepoints – was the fund’s bet on mortgage bonds of all types, according to a confidentialbreakdown of the fund’s returns obtained by Reuters.

  23. This site is crazy 🙂 donepezil reddit This disparity is unfair, the charity claims, saying those graduates worst hit will be the “squeezed middle” of their generation. High earning graduates who rapidly climb the income ladder would be etter off thn their middle-earning peers, because they would clear the debt more rapidly and thus pay less total interest.

  24. What’s the last date I can post this to to arrive in time for Christmas? citalopram pharmacy2us Bullard has been particularly outspoken on the issue, and released an unusually sharp statement to explain his dissent, although he voted with the majority at the July meeting after the inclusion of a low inflation warning in the statement.

  25. Why did you come to ? release my mind
    “This is not about politics; it's about recognising that we're living in a difficult economic climate where more people in poverty are struggling to cope and that we need to work together to find solutions so that the poorest and most vulnerable don't go hungry.”

Comments are closed.