Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Change permalink for WooCommerce product based on SKU and product name.
- *
- * @param string $url The generated permalink URL.
- * @param WP_Post $post The post object.
- * @return string The modified permalink URL.
- */
- function pm_sku_permalinks( $url, $post ) {
- if ( $post->post_type !== 'product' || $post->post_status !== 'publish' ) {
- return $url;
- }
- $product_sku = get_post_meta( $post->ID, SKU_FIELD, true );
- $product_name = $post->post_name;
- if ( empty( $product_sku ) || empty( $product_name ) ) {
- return $url;
- }
- $url = sprintf( "%s/%s/%s", get_home_url(), sanitize_title( $product_sku ), sanitize_title( $product_name ) );
- return user_trailingslashit( $url );
- }
- add_filter( 'post_type_link', 'pm_sku_permalinks', 999, 2 );
- /**
- * Detect WooCommerce product based on SKU and product name in the permalink.
- *
- * @param array $query The current query variables.
- *
- * @return array The modified query variables.
- */
- function pm_detect_sku_product_permalinks( $query ) {
- global $wpdb, $wp;
- // Do not run when Elementor is active
- if ( defined( 'ELEMENTOR_PATH' ) || isset( $_REQUEST['elementor-preview'] ) ) {
- return $query;
- }
- $request_path = trim( $wp->request, '/' );
- // Check if the request path matches the expected pattern
- if ( preg_match( '/^([^\/]+)\/([^\/]+)$/', $request_path, $matches ) ) {
- $sku_number = $matches[1];
- $product_name = $matches[2];
- // Check if the SKU is assigned to any product
- $sql_query = $wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} AS p
- INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id AND pm.meta_key = %s
- WHERE p.post_type = 'product' AND p.post_status = 'publish' AND pm.meta_value = %s", SKU_FIELD, $sku_number );
- $product_id = $wpdb->get_var( $sql_query );
- // If product found, set query variables accordingly
- if ( $product_id && get_post_field( 'post_name', $product_id ) === $product_name ) {
- $query['post_type'] = 'product';
- $query['name'] = $product_name;
- $query['do_not_redirect'] = 1;
- // Disable canonical redirect
- remove_action( 'template_redirect', 'wp_old_slug_redirect' );
- remove_action( 'template_redirect', 'redirect_canonical' );
- }
- }
- return $query;
- }
- add_filter( 'request', 'pm_detect_sku_product_permalinks', 9999 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement