ProductCatHooks.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\DisplayAsTranslated; |
| 4 | |
| 5 | use WPML\FP\Just; |
| 6 | use WPML\FP\Obj; |
| 7 | use WPML\LIB\WP\Hooks; |
| 8 | use function WPML\FP\invoke; |
| 9 | use function WPML\FP\spreadArgs; |
| 10 | |
| 11 | class ProductCatHooks implements \IWPML_Frontend_Action { |
| 12 | |
| 13 | private $isTermsFilterLoaded = false; |
| 14 | |
| 15 | const KEY_FIX_TERM_COUNT_ZERO = 'wcml_fix_term_count_zero'; |
| 16 | |
| 17 | private $elementFactory; |
| 18 | |
| 19 | public function __construct( \WPML_Translation_Element_Factory $elementFactory ) { |
| 20 | $this->elementFactory = $elementFactory; |
| 21 | } |
| 22 | |
| 23 | public function add_hooks() { |
| 24 | Hooks::onFilter( 'woocommerce_product_subcategories_args' ) |
| 25 | ->then( spreadArgs( [ $this, 'addFixCountArg' ] ) ); |
| 26 | } |
| 27 | |
| 28 | public function addFixCountArg( $args ) { |
| 29 | $this->loadTermsFilter(); |
| 30 | return (array) Obj::assoc( self::KEY_FIX_TERM_COUNT_ZERO, true, $args ); |
| 31 | } |
| 32 | |
| 33 | private function loadTermsFilter() { |
| 34 | if ( ! $this->isTermsFilterLoaded ) { |
| 35 | Hooks::onFilter( 'get_terms', 10, 4 ) |
| 36 | ->then( spreadArgs( [ $this, 'fixTermsWithZeroCount' ] ) ); |
| 37 | |
| 38 | $this->isTermsFilterLoaded = true; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public function fixTermsWithZeroCount( $terms, $taxonomy, $termQueryVars ) { |
| 43 | if ( ! empty( $termQueryVars[ self::KEY_FIX_TERM_COUNT_ZERO ] ) ) { |
| 44 | foreach ( $terms as $term ) { |
| 45 | if ( ! $term->count ) { |
| 46 | $term->count = $this->getSourceTermCount( $term ); |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | return $terms; |
| 52 | } |
| 53 | |
| 54 | private function getSourceTermCount( $term ) { |
| 55 | return (int) Just::of( $this->elementFactory->create_term( $term->term_taxonomy_id ) ) |
| 56 | ->map( invoke( 'get_source_element' ) ) |
| 57 | ->map( invoke( 'get_wp_object' ) ) |
| 58 | ->map( Obj::prop( 'count' ) ) |
| 59 | ->getOrElse( $term->count ); |
| 60 | } |
| 61 | } |
| 62 |