Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Detect product permalinks
- * URL Format: http://shop.com/product_slug/variation_sku
- */
- function pm_detect_product_permalinks($request) {
- global $wp, $wpdb;
- // Parse the URI
- preg_match('/^(?:([a-z]{2})\/)?([^\/]+)(?:\/([^\/]+))?\/?$/i', $wp->request, $parts);
- if(!empty($parts[2])) {
- $new_request = array();
- // Get product by slug
- $product = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s AND post_status = %s",
- sanitize_title($parts[2]),
- 'product',
- 'publish'
- ));
- // 1. Rewrite request array if product was found
- if(!empty($product->post_name)) {
- $new_request['name'] = $product->post_name;
- $new_request['post_type'] = 'product';
- $new_request['product'] = $product->post_name;
- $new_request['do_not_redirect'] = 1;
- }
- // 2. Get variation by SKU
- if(!empty($parts[3])) {
- $variation_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s",
- '_sku',
- sanitize_title($parts[3])
- ));
- if(is_numeric($variation_id)) {
- $product_variation = wc_get_product((int) $variation_id);
- $variation_variations = $product_variation->get_variation_attributes();
- // Preselect attributes
- if(!empty($variation_variations)) {
- foreach($variation_variations as $attr_name => $attr_value) {
- // $attr_name = str_replace('attribute_', '', $attr);
- $_REQUEST[$attr_name] = $attr_value;
- }
- }
- } else {
- return $request;
- }
- }
- $request = $new_request;
- }
- return $request;
- }
- add_filter('request', 'pm_detect_product_permalinks', 99);
- /**
- * Filter product permalinks
- */
- function bis_filter_woo_permalinks($url, $element) {
- if(!empty($element->post_type) && ($element->post_type == 'product')) {
- $url = trim(get_option('home'), '/') . "/{$element->post_name}";
- }
- return $url;
- }
- add_filter('post_type_link', 'bis_filter_woo_permalinks', 999, 2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement