WordPress at Your Fingertips
function is not described

WC_Admin_Duplicate_Product::generate_unique_slug() private WC 3.9.0

Generates a unique slug for a given product. We do this so that we can override the behavior of wp_unique_post_slug(). The normal slug generation will run single select queries on every non-unique slug, resulting in very bad performance.

{} It's a method of the class: WC_Admin_Duplicate_Product{}

No Hooks.

Return

null. Nothing.

Usage

// private - for code of main (parent) class only
$result = $this->generate_unique_slug( $product );
$product(WC_Product) (required)
The product to generate a slug for.

Changelog

Since 3.9.0 Introduced.

Code of WC_Admin_Duplicate_Product::generate_unique_slug() WC 5.9.0

private function generate_unique_slug( $product ) {
	global $wpdb;

	// We want to remove the suffix from the slug so that we can find the maximum suffix using this root slug.
	// This will allow us to find the next-highest suffix that is unique. While this does not support gap
	// filling, this shouldn't matter for our use-case.
	$root_slug = preg_replace( '/-[0-9]+$/', '', $product->get_slug() );

	$results = $wpdb->get_results(
		$wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name LIKE %s AND post_type IN ( 'product', 'product_variation' )", $root_slug . '%' )
	);

	// The slug is already unique!
	if ( empty( $results ) ) {
		return;
	}

	// Find the maximum suffix so we can ensure uniqueness.
	$max_suffix = 1;
	foreach ( $results as $result ) {
		// Pull a numerical suffix off the slug after the last hyphen.
		$suffix = intval( substr( $result->post_name, strrpos( $result->post_name, '-' ) + 1 ) );
		if ( $suffix > $max_suffix ) {
			$max_suffix = $suffix;
		}
	}

	$product->set_slug( $root_slug . '-' . ( $max_suffix + 1 ) );
}