Advertisement
mbis

Detect product attributes dynamically

Jul 20th, 2021
1,358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.96 KB | None | 0 0
  1. function pm_detect_product_attributes($query, $old_query, $uri_parts, $pm_query, $content_type) {
  2.     global $wpdb, $permalink_manager_uris;
  3.  
  4.     // Make sure that no custom permalink was detected by Permalink Manager
  5.     if(!empty($pm_query['id'])) {
  6.         return $query;
  7.     }
  8.  
  9.     // Make sure that $uri_parts variable is set correctly
  10.     if(empty($uri_parts['uri'])) {
  11.         return $query;
  12.     }
  13.  
  14.     // 1. Parse last two slugs from the requested URI
  15.     preg_match('/(.*)\/([^\/]+)\/([^\/]+)\/?$/', $uri_parts['uri'], $slugs);
  16.  
  17.     // 2. Check if any of slugs is a product attribute
  18.     if(!empty($slugs[3])) {
  19.         $possible_attributes = array($slugs[2], $slugs[3]);
  20.         $found_attributes = array();
  21.  
  22.         foreach($possible_attributes as $slug) {
  23.             $sql_query = "SELECT t.slug, t.term_id, tt.taxonomy FROM {$wpdb->terms} AS t INNER JOIN {$wpdb->term_taxonomy} AS tt ON(t.term_id = tt.term_id) WHERE 1=1 AND slug = %s";
  24.         $term = $wpdb->get_row($wpdb->prepare($sql_query, array($slug)));
  25.  
  26.             if(!empty($term->taxonomy)) {
  27.                 $found_attributes[$term->taxonomy] = $term->slug;
  28.  
  29.                 // OPTIONAL. Keep the below line to preselect the attribute in the add-to-cart form
  30.                 $_REQUEST["attribute_{$term->taxonomy}"] = $term->slug;
  31.             }
  32.         }
  33.  
  34.         // 3. Check if the rest of URI is a custom permalink
  35.         $post_id = array_search($slugs[1], $permalink_manager_uris);
  36.  
  37.         // 3A. Second attempt
  38.         if(empty($post_id)) {
  39.             $post_id = array_search("{$slugs[1]}/$slugs[2]", $permalink_manager_uris);
  40.         }
  41.  
  42.         // 4. Change the final query if the post (product) is found
  43.         if(!empty($post_id)) {
  44.             $post_object = get_post($post_id);
  45.  
  46.             if(!empty($post_object->post_type) && $post_object->post_type == 'product') {
  47.                 $query = array(
  48.                     'name' => $post_object->post_name,
  49.                     'post_type' => $post_object->post_type,
  50.                     'product' => $post_object->post_name,
  51.                     'do_not_redirect' => 1
  52.                 );
  53.             }
  54.         }
  55.     }
  56.  
  57.     return $query;
  58. }
  59. add_filter('permalink_manager_filter_query', 'pm_detect_product_attributes', 3, 5);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement