wc_product_post_type_link

Filter to allow product_cat in the permalinks for products.

Description

(string) wc_product_post_type_link( (string) $permalink, (WP_Post) $post ); 

Returns (string)

Parameters (2)

0. $permalink (string)
The existing permalink URL.
1. $post (WP_Post)
The post.

Usage

  1. if ( !function_exists( 'wc_product_post_type_link' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-product-functions.php'; 
  3.  
  4. // The existing permalink URL. 
  5. $permalink = ''; 
  6.  
  7. // The post. 
  8. $post = null; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wc_product_post_type_link($permalink, $post); 
  12.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-product-functions.php  
  1. function wc_product_post_type_link( $permalink, $post ) { 
  2. // Abort if post is not a product. 
  3. if ( 'product' !== $post->post_type ) { 
  4. return $permalink; 
  5.  
  6. // Abort early if the placeholder rewrite tag isn't in the generated URL. 
  7. if ( false === strpos( $permalink, '%' ) ) { 
  8. return $permalink; 
  9.  
  10. // Get the custom taxonomy terms in use by this post. 
  11. $terms = get_the_terms( $post->ID, 'product_cat' ); 
  12.  
  13. if ( ! empty( $terms ) ) { 
  14. if ( function_exists( 'wp_list_sort' ) ) { 
  15. $terms = wp_list_sort( $terms, 'term_id', 'ASC' ); 
  16. } else { 
  17. usort( $terms, '_usort_terms_by_ID' ); 
  18. $category_object = apply_filters( 'wc_product_post_type_link_product_cat', $terms[0], $terms, $post ); 
  19. $category_object = get_term( $category_object, 'product_cat' ); 
  20. $product_cat = $category_object->slug; 
  21.  
  22. if ( $category_object->parent ) { 
  23. $ancestors = get_ancestors( $category_object->term_id, 'product_cat' ); 
  24. foreach ( $ancestors as $ancestor ) { 
  25. $ancestor_object = get_term( $ancestor, 'product_cat' ); 
  26. $product_cat = $ancestor_object->slug . '/' . $product_cat; 
  27. } else { 
  28. // If no terms are assigned to this post, use a string instead (can't leave the placeholder there) 
  29. $product_cat = _x( 'uncategorized', 'slug', woocommerce ); 
  30.  
  31. $find = array( 
  32. '%year%',  
  33. '%monthnum%',  
  34. '%day%',  
  35. '%hour%',  
  36. '%minute%',  
  37. '%second%',  
  38. '%post_id%',  
  39. '%category%',  
  40. '%product_cat%',  
  41. ); 
  42.  
  43. $replace = array( 
  44. date_i18n( 'Y', strtotime( $post->post_date ) ),  
  45. date_i18n( 'm', strtotime( $post->post_date ) ),  
  46. date_i18n( 'd', strtotime( $post->post_date ) ),  
  47. date_i18n( 'H', strtotime( $post->post_date ) ),  
  48. date_i18n( 'i', strtotime( $post->post_date ) ),  
  49. date_i18n( 's', strtotime( $post->post_date ) ),  
  50. $post->ID,  
  51. $product_cat,  
  52. $product_cat,  
  53. ); 
  54.  
  55. $permalink = str_replace( $find, $replace, $permalink ); 
  56.  
  57. return $permalink;