| 1 |
<?php |
| 2 |
namespace Hurrytimer; |
| 3 |
|
| 4 |
class WC_Countdown |
| 5 |
{ |
| 6 |
public function get_wc_countdowns() |
| 7 |
{ |
| 8 |
$countdowns = get_posts([ |
| 9 |
'post_type' => HURRYTIMER_COUNTDOWN_PT, |
| 10 |
'posts_per_page' => -1, |
| 11 |
'post_status' => 'publish', |
| 12 |
'meta_key' => 'wc_enable', |
| 13 |
'meta_value' => "true", |
| 14 |
]); |
| 15 |
|
| 16 |
return array_map(function ($item) { |
| 17 |
return new Hurrytimer_Countdown($item->ID); |
| 18 |
}, $countdowns); |
| 19 |
} |
| 20 |
public function maybe_show_countdown($product_id) |
| 21 |
{ |
| 22 |
$countdowns = $this->get_wc_countdowns(); |
| 23 |
$categories = $this->get_product_categories($product_id); |
| 24 |
|
| 25 |
foreach ($countdowns as $countdown) { |
| 26 |
if ($this->can_run_countdown_timer($countdown, $product_id, $categories)) { |
| 27 |
add_action('woocommerce_single_product_summary', function () use ($countdown) { |
| 28 |
$this->show_shortcode($countdown); |
| 29 |
}, $countdown->get_position(), [$countdown->get_id()]); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
} |
| 34 |
|
| 35 |
public function can_run_countdown_timer($countdown, $product_id, $categories) |
| 36 |
{ |
| 37 |
$p_type = $countdown->get_products_type(); |
| 38 |
|
| 39 |
switch ($p_type) { |
| 40 |
case WC_Product_Selection::ALL_PRODUCTS: |
| 41 |
return true; |
| 42 |
case WC_Product_Selection::SPECIFIC_PRODUCTS: |
| 43 |
|
| 44 |
return in_array($product_id, $countdown->get_products()); |
| 45 |
case WC_Product_Selection::ALL_PRODUCTS_EXCEPT: |
| 46 |
return !in_array($product_id, $countdown->get_products()); |
| 47 |
case WC_Product_Selection::SPECIFIC_CATEGORIES: |
| 48 |
$included_categories = $countdown->get_products(); |
| 49 |
$results = array_filter($included_categories, function ($id) use ($categories) { |
| 50 |
return in_array($id, $categories); |
| 51 |
}); |
| 52 |
return count($results) > 0; |
| 53 |
case WC_Product_Selection::ALL_CATEGORIES_EXCEPT: |
| 54 |
$excluded_categories = $countdown->get_products(); |
| 55 |
$results = array_filter($excluded_categories, function ($id) use ($categories) { |
| 56 |
return !in_array($id, $categories); |
| 57 |
}); |
| 58 |
return count($results) > 0; |
| 59 |
default: |
| 60 |
return false; |
| 61 |
} |
| 62 |
|
| 63 |
} |
| 64 |
|
| 65 |
public function get_product_categories($product_id) |
| 66 |
{ |
| 67 |
return wp_get_object_terms($product_id, 'product_cat', ['fields' => 'ids']); |
| 68 |
} |
| 69 |
|
| 70 |
public function show_shortcode($countdown) |
| 71 |
{ |
| 72 |
$shortcode = '[hurrytimer id=' . $countdown->get_id() . ']'; |
| 73 |
echo do_shortcode($shortcode); |
| 74 |
} |
| 75 |
} |
| 76 |
|