Hooks.php
58 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\Terms\Count; |
| 4 | |
| 5 | use WCML\Terms\SuspendWpmlFiltersFactory; |
| 6 | use WPML\FP\Fns; |
| 7 | use WPML\FP\Obj; |
| 8 | use WPML\LIB\WP\Hooks as WpHooks; |
| 9 | use WCML\Utilities\WCTaxonomies; |
| 10 | use function WPML\FP\spreadArgs; |
| 11 | |
| 12 | class Hooks implements \IWPML_Backend_Action, \IWPML_REST_Action { |
| 13 | |
| 14 | public function add_hooks() { |
| 15 | WpHooks::onFilter( 'woocommerce_product_recount_terms', PHP_INT_MAX ) |
| 16 | ->then( spreadArgs( [ self::class, 'disableTermFilters' ] ) ); |
| 17 | |
| 18 | WpHooks::onAction( 'icl_save_term_translation', 10, 2 ) |
| 19 | ->then( spreadArgs( [ self::class, 'recountOnSaveTermTranslation' ] ) ); |
| 20 | |
| 21 | WpHooks::onAction( 'wpml_sync_term_hierarchy_done' ) |
| 22 | ->then( [ self::class, 'recountAllTermsInShutdown' ] ); |
| 23 | } |
| 24 | |
| 25 | public static function disableTermFilters( $shouldRecountTerms ) { |
| 26 | if ( $shouldRecountTerms ) { |
| 27 | $filtersSuspend = SuspendWpmlFiltersFactory::create(); |
| 28 | |
| 29 | add_action( 'delete_transient_wc_term_counts', function() use ( $filtersSuspend ) { |
| 30 | $filtersSuspend->resume(); |
| 31 | } ); |
| 32 | |
| 33 | } |
| 34 | |
| 35 | return $shouldRecountTerms; |
| 36 | } |
| 37 | |
| 38 | public static function recountOnSaveTermTranslation( $originalTax, $translatedTerm ) { |
| 39 | $taxonomyName = Obj::prop( 'taxonomy', $originalTax ); |
| 40 | |
| 41 | if ( in_array( $taxonomyName, [ WCTaxonomies::TAXONOMY_PRODUCT_CATEGORY, WCTaxonomies::TAXONOMY_PRODUCT_TAG ], true ) ) { |
| 42 | SuspendWpmlFiltersFactory::create()->runAndResume( function () use ( $translatedTerm, $taxonomyName ) { |
| 43 | _wc_term_recount( [ (int) Obj::prop( 'term_taxonomy_id', $translatedTerm ) ], get_taxonomy( $taxonomyName ) ); |
| 44 | } ); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | public static function recountAllTermsInShutdown() { |
| 49 | WpHooks::onAction( 'shutdown' )->then( Fns::once( [ self::class, 'recountAllTerms' ] ) ); |
| 50 | } |
| 51 | |
| 52 | public static function recountAllTerms() { |
| 53 | SuspendWpmlFiltersFactory::create()->runAndResume( function() { |
| 54 | wc_recount_all_terms(); |
| 55 | } ); |
| 56 | } |
| 57 | } |
| 58 |