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

286 thoughts on “WordPress Post Inserts Are Super Slow

  1. Horace says:

    This site is crazy 🙂 pes alpha t2 australia He said his choices include hacking the software that analyzes the fingerprint data, or physically opening up the phone and connecting it to a custom-built device that would impersonate Apple’s fingerprint reader.

  2. Shane says:

    I’m originally from Dublin but now live in Edinburgh where to buy accutane in the philippines The specialty value retailer on Tuesday announced asecondary offering by its shareholders. The company saidshareholders have agreed to sell 7.1 million shares of itscommon stock, of which 7 million shares would be sold by fundsaffiliated with Advent International and 100,000 shares will besold by Five Below’s executive chairman.

  3. Rodrick says:

    We need someone with qualifications total eclipse rely detox directions The state-level markets were designed to be the gateway to health insurance for people who don’t have access to coverage on the job. Middle-class consumers will be able to buy government-subsidized private plans, while the poor and near-poor will be steered to Medicaid in states agreeing to expand the program.

  4. Giovanni says:

    Could you tell me the number for ? tofranil nursing implications David Morens, an influenza researcher and senior adviser at the US National Institutes of Health in Bethesda, Maryland, says that the evolutionary pathway that the viruses followed suggests that more surveillance and better sanitation practices at poultry markets are crucial to monitoring risks to human health.

  5. Pierre says:

    It’s serious cheap strattera online China saw a broad-based recovery in major economicindicators for August, boding well for the economy’s prospectsfor the remainder of the year and prompting several foreignbanks to revise up their forecasts for annual GDP growth in2013.

  6. Fidel says:

    I’d like to tell you about a change of address udenafil pde5 Greenberg might perhaps have added a twist too many to his Hitchcockian tale, in which nobody is quite what they appear to be – but it is so well acted, and ably directed by David Grindley, that it seems churlish to dwell too much upon it. Exceptionally strong ensemble casts can, in any case, triumph over flawed material, and this is why I think the production managed to keep me hooked until the very end.

  7. Jeromy says:

    We’re at university together wellbutrin xl 150 mg fiyat ne kadar “We had lovely sweet little eight-year-old girls shooting massive shotguns but they didn’t then go around killing everyone afterwards; they just saw it as an activity that they enjoyed,” he said.

  8. Jasmine says:

    Just over two years zn pharma santos But does Labour really have cause to be proud of its record on the NHS? Today, the results of an investigation into suspicious death rates at 14 hospitals – carried out in the wake of the scandals at Mid Staffordshire – are revealed. The facts are appalling: their performance was so poor that up to 13,000 people may have died needlessly. So severe are the problems that Prof Sir Bruce Keogh, the medical director of NHS England, is expected to place many in special measures, or replace management teams entirely.

  9. Hayden says:

    Sorry, I ran out of credit taraskincare.net The 11.4-km (7-mile) Gudvanga tunnel, Norway’s secondlongest, carries traffic close to the Naeroey fjord, consideredone of its most beautiful and a draw for tourists from aroundthe world during the summer season.

  10. Raymond says:

    I went to fluoxetine dose escalation Bobby Abreu’s single in the fifth turned out to be his final hit of his 18-year career

  11. Refugio says:

    Do you need a work permit? olmesartan medoxomil fda warning Hong Kong is governed under the principle of “one country, two systems”, under which China has agreed to give the region a high degree of autonomy and to preserve its economic and social systems for 50 years from the date of the handover.

  12. Scottie says:

    Cool site goodluck 🙂 adiponectinsupplement.net Wilkerson is in the Top 5 in quarterback hurries and quarterback pressures among 3-4 defensive linemen, according to Pro Football Focus. He’s in the Top 10 among 3-4 defensive ends in run-stop percentage.

  13. Noah says:

    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.

  14. Quentin says:

    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.

  15. Keenan says:

    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.

  16. Gregorio says:

    I’m not sure is it safe to take tylenol and motrin at the same time For many the covert trip through Brooks County, 70 miles from the Rio Grande Valley border crossing, has become a death trap of temperatures in the triple digits, thick mesquite brush and sand that is a foot deep in places.

  17. Mike says:

    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.”

  18. Tristan says:

    This is your employment contract hyzaar forte etken madde The central bank only has several dozen insurance experts spread throughout its organization, versus more than 400 banking experts in its Washington headquarters alone.

  19. Korey says:

    Three years harga captopril 25 A number of Android tablet apps are free and ad-supported, while their iOS counterparts require some payment. While this might seem like Android users get the better end of the deal, Canalys said that ad-supported apps usually offer a poorer and more limited user experience, “subjecting users to unskippable videos or other unpopular intrusions,” said Canalys analyst Daniel Matte.

  20. Bob says:

    I’ve just graduated parisi approved training peaks Mr Marr added: “I am immensely proud of all that NHS Tayside has achieved over the past few years but I am even prouder of the fact that, thanks to the dedication of all staff at all levels, the people of Tayside have health services they can have confidence in.”

  21. Clarence says:

    Canada>Canada health-express.co.uk “One of the toughest things I’ve ever had to do,” Cooper said of the meeting. “It was extremely emotional. They could tell I was sincere, but it was tough… I’m hoping we can rally around this and my teammates will be behind me and I’ll get through this.”

  22. Efren says:

    Who would I report to? nootropicsmexico.com review
    “Parents often know other families who have done it, so they want to ‘keep up with the Joneses’, or their kid asks to go,” he said. Many parents also consider sending their children, when older, to study full-time overseas.

  23. Randolph says:

    Jonny was here astralean for sale uk Chief Financial Officer Wayne DeVeydt said that the companystill must determine how many current customers will migrate tothe exchanges and how much it will need to spend to support theplans there to gauge its 2014 performance.

  24. Modesto says:

    I’d like to open a personal account novum medical products clarence Airbus’ program director of innovation, Alain Fontaine, says this new approach to building structures “is really disruptive. It opens interesting opportunities in the way to design and manufacture aerostructures.” These technologies, he says, “can open the door to other opportunities” and have major potential to lower manufacturing costs.

  25. Jose says:

    I’m a member of a gym how effective is paxil for depression “It’s not just about ‘x’ percent weight loss, it’s making achange in the fundamental underlying metabolic disease, thatwill probably go on to reduce the cost of the healthcare systemand save lives of these patients,” Third Rock’s Starr said.

  26. Tyree says:

    This is your employment contract conair infiniti pro secret wave – cd204c “That was his main motivation in exposing the documents,” said Smith. “He was hoping that someone with a badge would show up and no one did. They have expressed interest before, but now they are actually doing something,” he added.

  27. Harris says:

    How much will it cost to send this letter to ? pharmoutcomes.org Dropbox today announced a new API and feature set collectively called the Dropbox Platform that will allow users to more easily maintain one online identity and sync settings, files and data across multiple apps, platforms and services.

  28. Malcom says:

    Thanks funny site buy priligy thailand It was not immediately clear what the warrant was issued for but Gross — who has been imprisoned on Rikers Island since the Aug. 11 collar in Gramercy — said he thought it was because of a subsequent bust.

  29. Timmy says:

    In tens, please (ten pound notes) naprosyn yahoo answers
    They are not all created equal. Some spend the bulk of theirmoney fundraising, have poor financial controls and highly paidexecutives. Some focus on research, others on putting outpreventive care messages. Some have highly rated operations butfunnel money in ways that might not fit your own socialobjectives – supporting (or not) Planned Parenthood’s breastcancer testing facilities, for example.

  30. Tyron says:

    Children with disabilities oral prednisolone athletic performance We don’t envisage that such a policy would lead to a mass exodus of patients from GP practices, but the potential that they could would give them much greater influence over the way services developed.”

  31. Rashad says:

    History promethazine 6.25 mg 5ml syrup dosage The Sallie Mae report also reinforced evidence that families are increasingly choosing where to apply for college based on cost. Last year, 67% of families eliminated colleges based on cost during the admissions process, up from 56% in 2009.

  32. Andreas says:

    Your account’s overdrawn what does costco pay pharmacy technicians
    United, which was formed by a merger of UAL and Continentalin 2010, has been working to win back customers who turned torivals after the airline faced severe service-related andoperational problems last year.

  33. Julius says:

    Have you read any good books lately? comaldrug.com Microsoft posted its Q4 financials, and for those of you wondering if it has enough cash in its pocket to buy lunch, the answer is yes. Revenue grew to $19.896 billion, representing a 10% increase over 2012, but there’s a catch; not all of that revenue is real growth. Most of it relates to one-off special events – a deferral of cash earned in 2012 associated with the Windows Upgrade Offer, and a chunk of change that came with the Office Upgrade Offer – which means that, of that 10%, only 3% ($515 million) represents actual honest-to-Wall Street growth in its markets. As you might expect, its office and business segments were the ones bringing home the bacon, but entertainment did modestly well. Even including a slowing Xbox 360 market – wouldn’t you know it, in the year Microsoft announced a new console, people stopped buying the old one – the entertainment division’s revenue increased by 8% ($134 million), due mainly to higher Windows Phone earnings.

  34. Kelvin says:

    Will I be paid weekly or monthly? french pharmacy dry shampoo The April 17 blast at the West Fertilizer Co flattened homesand caused an estimated $100 million in damages toneighborhoods, businesses and schools in West, Texas, about 80miles south of Dallas. The dead included 11 firefighters andother first responders who had rushed to contain a fire at theplant moments before the blast.

  35. Melissa says:

    What are the hours of work? prix xeloda 500 Stupidity is not the problem at all. The novelist Milan Kundera points out that it was once thought that stupidity could be easily cured with knowledge; that was wrong. The addiction to influential power based in untruths modernizes itself with everything else. Propaganda has become a popular melodrama, especially when driven by self-pity.

  36. Bruno says:

    I stay at home and look after the children celexa dose equivalent to lexapro Prime Minister Mark Rutte’s government summoned Russia’s ambassador in The Hague to explain Tuesday’s assault, in which the second-in-charge of the Dutch embassy in Moscow was attacked at his home by unknown intruders posing as electricians.

Leave a Reply

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