Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pm_detect_product_attributes($query, $old_query, $uri_parts, $pm_query, $content_type) {
- global $wpdb, $permalink_manager_uris;
- // Make sure that no custom permalink was detected by Permalink Manager
- if(!empty($pm_query['id'])) {
- return $query;
- }
- // Make sure that $uri_parts variable is set correctly
- if(empty($uri_parts['uri'])) {
- return $query;
- }
- // 1. Parse last two slugs from the requested URI
- preg_match('/(.*)\/([^\/]+)\/([^\/]+)\/?$/', $uri_parts['uri'], $slugs);
- // 2. Check if any of slugs is a product attribute
- if(!empty($slugs[3])) {
- $possible_attributes = array($slugs[2], $slugs[3]);
- $found_attributes = array();
- foreach($possible_attributes as $slug) {
- $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";
- $term = $wpdb->get_row($wpdb->prepare($sql_query, array($slug)));
- if(!empty($term->taxonomy)) {
- $found_attributes[$term->taxonomy] = $term->slug;
- // OPTIONAL. Keep the below line to preselect the attribute in the add-to-cart form
- $_REQUEST["attribute_{$term->taxonomy}"] = $term->slug;
- }
- }
- // 3. Check if the rest of URI is a custom permalink
- $post_id = array_search($slugs[1], $permalink_manager_uris);
- // 3A. Second attempt
- if(empty($post_id)) {
- $post_id = array_search("{$slugs[1]}/$slugs[2]", $permalink_manager_uris);
- }
- // 4. Change the final query if the post (product) is found
- if(!empty($post_id)) {
- $post_object = get_post($post_id);
- if(!empty($post_object->post_type) && $post_object->post_type == 'product') {
- $query = array(
- 'name' => $post_object->post_name,
- 'post_type' => $post_object->post_type,
- 'product' => $post_object->post_name,
- 'do_not_redirect' => 1
- );
- }
- }
- }
- return $query;
- }
- add_filter('permalink_manager_filter_query', 'pm_detect_product_attributes', 3, 5);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement