_wp_batch_update_comment_type()

In this article

Updates the comment type for a batch of comments.

Source

function _wp_batch_update_comment_type() {
	global $wpdb;

	$lock_name = 'update_comment_type.lock';

	// Try to lock.
	$lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );

	if ( ! $lock_result ) {
		$lock_result = get_option( $lock_name );

		// Bail if we were unable to create a lock, or if the existing lock is still valid.
		if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
			wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
			return;
		}
	}

	// Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
	update_option( $lock_name, time() );

	// Check if there's still an empty comment type.
	$empty_comment_type = $wpdb->get_var(
		"SELECT comment_ID FROM $wpdb->comments
		WHERE comment_type = ''
		LIMIT 1"
	);

	// No empty comment type, we're done here.
	if ( ! $empty_comment_type ) {
		update_option( 'finished_updating_comment_type', true );
		delete_option( $lock_name );
		return;
	}

	// Empty comment type found? We'll need to run this script again.
	wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );

	/**
	 * Filters the comment batch size for updating the comment type.
	 *
	 * @since 5.5.0
	 *
	 * @param int $comment_batch_size The comment batch size. Default 100.
	 */
	$comment_batch_size = (int) apply_filters( 'wp_update_comment_type_batch_size', 100 );

	// Get the IDs of the comments to update.
	$comment_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT comment_ID
			FROM {$wpdb->comments}
			WHERE comment_type = ''
			ORDER BY comment_ID DESC
			LIMIT %d",
			$comment_batch_size
		)
	);

	if ( $comment_ids ) {
		$comment_id_list = implode( ',', $comment_ids );

		// Update the `comment_type` field value to be `comment` for the next batch of comments.
		$wpdb->query(
			"UPDATE {$wpdb->comments}
			SET comment_type = 'comment'
			WHERE comment_type = ''
			AND comment_ID IN ({$comment_id_list})" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		);

		// Make sure to clean the comment cache.
		clean_comment_cache( $comment_ids );
	}

	delete_option( $lock_name );
}

Hooks

apply_filters( ‘wp_update_comment_type_batch_size’, int $comment_batch_size )

Filters the comment batch size for updating the comment type.

Changelog

VersionDescription
5.5.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.