mbis

Support %category% tag for 'attachment' post type

Dec 15th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Support %category% tag for 'attachment' post type
  3.  */
  4. function pm_support_category_tag( $default_uri, $native_slug, $post, $slug, $native_uri ) {
  5.     if ( $native_uri || empty( $post->post_type ) || empty( $post->post_parent ) || $post->post_type !== 'attachment' ) {
  6.         return $default_uri;
  7.     }
  8.  
  9.     // 1. Get terms assigned to parent post
  10.     $taxonomy = 'category';
  11.     $rel_post = $post->post_parent;
  12.     $terms    = wp_get_object_terms( $rel_post, $taxonomy );
  13.  
  14.     // 2. Sort the terms
  15.     if ( ! empty( $terms ) ) {
  16.         $terms = wp_list_sort( $terms, array(
  17.             'parent'  => 'DESC',
  18.             'term_id' => 'ASC',
  19.         ) );
  20.     }
  21.  
  22.     // 3A. Try to use Yoast SEO Primary Term
  23.     $replacement_term = Permalink_Manager_Helper_Functions::get_primary_term( $rel_post, $taxonomy, false );
  24.  
  25.     // 3B. Get the first assigned term to this taxonomy
  26.     if ( empty( $replacement_term ) ) {
  27.         $replacement_term = ( ! is_wp_error( $terms ) && ! empty( $terms ) && is_object( $terms[0] ) ) ? Permalink_Manager_Helper_Functions::get_lowest_element( $terms[0], $terms ) : '';
  28.         $replacement_term = apply_filters( 'permalink_manager_filter_post_terms', $replacement_term, $rel_post, $terms, $taxonomy, $native_uri );
  29.     }
  30.  
  31.     $replacement = Permalink_Manager_Helper_Functions::get_term_full_slug( $replacement_term, $terms, 2, $native_uri );
  32.  
  33.     return str_replace( '%category%', $replacement, $default_uri );
  34. }
  35. add_filter( 'permalink_manager_filter_default_post_uri', 'pm_support_category_tag', 10, 5 );
Add Comment
Please, Sign In to add comment