Advertisement
mbis

Detect product attributes after /product/%product%

Nov 20th, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. function pm_detect_dynamic_product_attributes( $uri_parts, $request_url, $endpoints ) {
  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 $uri_parts;
  7.     }
  8.  
  9.     // Make sure that $uri_parts variable is set correctly
  10.     if ( empty( $uri_parts['uri'] ) ) {
  11.         return $uri_parts;
  12.     }
  13.  
  14.     // 1. Separate "product/%product%" from rest of URL
  15.     preg_match( '/^(product\/[^\/]+)\/(.*)/', $uri_parts['uri'], $slugs );
  16.  
  17.     // 2. Check if any of slugs is a product attribute
  18.     if ( ! empty( $slugs[2] ) ) {
  19.         $found_attributes    = array();
  20.         $possible_attributes = explode( "/", $slugs[2] );
  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 product URI is a custom permalink
  35.         $product_id = array_search( $slugs[1], $permalink_manager_uris );
  36.  
  37.         // 4. Change the final query if the post (product) is found
  38.         if ( ! empty( $product_id ) ) {
  39.             $post_object = get_post( $product_id );
  40.  
  41.             if ( ! empty( $post_object->post_type ) && $post_object->post_type == 'product' ) {
  42.                 $uri_parts['uri'] = $slugs[1];
  43.                
  44.                 // You can use the $found_attributes array in your custom code
  45.             }
  46.         }
  47.     }
  48.  
  49.     return $uri_parts;
  50. }
  51. add_filter( 'permalink_manager_detect_uri', 'pm_detect_dynamic_product_attributes', 20, 3 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement