The function get_product_id_by_slug
takes a product slug (a URL-friendly version of the product name) as input. It first validates and sanitizes the input to ensure it’s a secure, non-empty string. Then, it uses the WordPress function get_page_by_path
to attempt to retrieve a post object that matches this slug, specifically looking for a post of type ‘product’, which is typically used in WooCommerce. If a matching product is found, the function returns the product’s ID. If no matching product is found or if the input is invalid, the function returns null. This functionality is primarily used in WooCommerce contexts to find products based on their slugs.
<?php function get_product_id_by_slug($slug) { if (!is_string($slug) || empty($slug)) { // Validate input to ensure it's a non-empty string. return null; } // Sanitize the slug to avoid any potential security issues. $sanitized_slug = sanitize_title($slug); $product = get_page_by_path($sanitized_slug, OBJECT, 'product'); if ($product && is_a($product, 'WP_Post')) { return (int) $product->ID; // Cast ID to integer for consistency. } return null; }