3 class WPML_ST_Term_Link_Filter {
5 const CACHE_GROUP = 'WPML_ST_Term_Link_Filter::replace_base_in_permalink_structure';
7 /** @var SitePress $sitepress */
10 /** @var WPML_Tax_Slug_Translation_Records $slug_records */
11 private $slug_records;
13 /** @var WPML_WP_Cache_Factory $cache_factory */
14 private $cache_factory;
16 public function __construct(
17 WPML_Tax_Slug_Translation_Records $slug_records,
19 WPML_WP_Cache_Factory $cache_factory
21 $this->slug_records = $slug_records;
22 $this->sitepress = $sitepress;
23 $this->cache_factory = $cache_factory;
27 * Filters the permalink structure for a terms before token replacement occurs
28 * with the hook filter `pre_term_link` available since WP 4.9.0
32 * @param false|string $termlink
33 * @param WP_Term $term
35 * @return false|string
37 public function replace_slug_in_termlink( $termlink, $term ) {
38 if ( ! $termlink || ! $this->sitepress->is_translated_taxonomy( $term->taxonomy ) ) {
42 $term_lang = $this->sitepress->get_language_for_element( $term->term_taxonomy_id, 'tax_' . $term->taxonomy );
43 $cache_key = $termlink . $term_lang;
44 $cache_item = $this->cache_factory->create_cache_item( self::CACHE_GROUP, $cache_key );
46 if ( $cache_item->exists() ) {
47 $termlink = $cache_item->get();
49 $original_slug = $this->slug_records->get_original( $term->taxonomy );
50 $translated_slug = $this->slug_records->get_translation( $term->taxonomy, $term_lang );
52 if ( $original_slug && $translated_slug && $original_slug !== $translated_slug ) {
53 $termlink = $this->replace_slug( $termlink, $original_slug, $translated_slug );
56 $cache_item->set( $termlink );
63 * @param string $termlink
64 * @param string $original_slug
65 * @param string $translated_slug
69 private function replace_slug( $termlink, $original_slug, $translated_slug ) {
70 if ( preg_match( '#/?' . preg_quote( $original_slug ) . '/#', $termlink ) ) {
71 $termlink = preg_replace(
72 '#^(/?)(' . addslashes( $original_slug ) . ')/#',
73 "$1$translated_slug/",