Guest User

Untitled

a guest
Nov 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4. add_filter('post_link', 'rudr_post_type_permalink', 20, 3);
  5. add_filter('post_type_link', 'rudr_post_type_permalink', 20, 3);
  6.  
  7. function rudr_post_type_permalink($permalink, $post_id, $leavename) {
  8.  
  9. $post_type_name = 'product'; // post type name, you can find it in admin area or in register_post_type() function
  10. $post_type_slug = 'product'; // the part of your product URLs, not always matches with the post type name
  11. $tax_name = 'product_cat'; // the product categories taxonomy name
  12.  
  13. $post = get_post( $post_id );
  14.  
  15. if ( strpos( $permalink, $post_type_slug ) === FALSE || $post->post_type != $post_type_name ) // do not make changes if the post has different type or its URL doesn't contain the given post type slug
  16. return $permalink;
  17.  
  18. $terms = wp_get_object_terms( $post->ID, $tax_name ); // get all terms (product categories) of this post (product)
  19.  
  20.  
  21. if ( !is_wp_error( $terms ) && !empty( $terms ) && is_object( $terms[0] ) ) // rewrite only if this product has categories
  22. $permalink = str_replace( $post_type_slug, $terms[0]->slug, $permalink );
  23.  
  24. return $permalink;
  25. }
  26.  
  27.  
  28. add_filter('request', 'rudr_post_type_request', 1, 1 );
  29.  
  30. function rudr_post_type_request( $query ){
  31. global $wpdb;
  32.  
  33. $post_type_name = 'product'; // specify your own here
  34. $tax_name = 'product_cat'; // and here
  35.  
  36. $slug = $query['attachment']; // when we change the post type link, WordPress thinks that these are attachment pages
  37.  
  38. // get the post with the given type and slug from the database
  39. $post_id = $wpdb->get_var(
  40. "
  41. SELECT ID
  42. FROM $wpdb->posts
  43. WHERE post_name = '$slug'
  44. AND post_type = '$post_type_name'
  45. "
  46. );
  47.  
  48. $terms = wp_get_object_terms( $post_id, $tax_name ); // our post should have the terms
  49.  
  50.  
  51. if( isset( $slug ) && $post_id && !is_wp_error( $terms ) && !empty( $terms ) ) : // change the query
  52.  
  53. unset( $query['attachment'] );
  54. $query[$post_type_name] = $slug;
  55. $query['post_type'] = $post_type_name;
  56. $query['name'] = $slug;
  57.  
  58. endif;
  59.  
  60. return $query;
  61. }
Add Comment
Please, Sign In to add comment