• Flamingo_Inbound_Message::save() is very slow when inserting a new submission when there are already thousands of submissions with the same NAME (several seconds when tens of thousands)
    It is because wp_insert_post() is called without passing the post_name and so it tries to find a unique post_name (=slug which must be unique per post type).
    It looks up to see if there is already a post of that type with the name (sanitize_title).
    If so, it then checks again using name-2.
    If still found, it adds one to the suffix so -3, and so on until it finds a name not used.
    When there are THOUSANDS of matching posts, this takes a few seconds even on MariaDB 10.11 with index-wp-for-speed plugin used to add nice indexes.

    I have inserted the following just before the call to wp_insert_post():

    // Post slugs must be unique across all posts.
    global $wpdb;
    $slug = sanitize_title($postarr['post_title']);
    $post_type = $postarr['post_type'];
    $post_id = $postarr['ID'];
    $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
    $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
    if($post_name_check) {
    // we have a post with that name already
    $suffix = 2;
    $alt_post_name = $slug.'-';
    // find the BIGGEST suffix from the DB
    $check_sql = "SELECT CAST(SUBSTRING(post_name,LENGTH(%s)+1) AS INTEGER) FROM $wpdb->posts WHERE post_name LIKE %s AND post_type=%s AND ID != %3d ORDER BY 1 DESC LIMIT 1";
    $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $alt_post_name.'%', $post_type, $post_ID ) );
    if($post_name_check) {
    $suffix = absint($post_name_check)+1; // number from DB plus one
    }
    $slug .= '-'.$suffix; // either next suffix from DB or 2
    $postarr['post_name'] = $slug;
    } else {
    // we DONT have a post with that name already, and can save a db query later by specifying the name here
    $postarr['post_name'] = $slug;
    }
  • The topic ‘Form submissions slow when lots of submissions already’ is closed to new replies.