Admin
4 years ago
DataStores
4 years ago
DependencyManagement
4 years ago
ProductAttributesLookup
4 years ago
ProductDownloads
4 years ago
Settings
4 years ago
Utilities
4 years ago
WCCom
5 years ago
AssignDefaultCategory.php
5 years ago
DownloadPermissionsAdjuster.php
5 years ago
RestApiUtil.php
4 years ago
RestockRefundedItemsAdjuster.php
4 years ago
AssignDefaultCategory.php
74 lines
| 1 | <?php |
| 2 | /** |
| 3 | * AssignDefaultCategory class file. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Internal; |
| 7 | |
| 8 | defined( 'ABSPATH' ) || exit; |
| 9 | |
| 10 | /** |
| 11 | * Class to assign default category to products. |
| 12 | */ |
| 13 | class AssignDefaultCategory { |
| 14 | /** |
| 15 | * Class initialization, to be executed when the class is resolved by the container. |
| 16 | * |
| 17 | * @internal |
| 18 | */ |
| 19 | final public function init() { |
| 20 | add_action( 'wc_schedule_update_product_default_cat', array( $this, 'maybe_assign_default_product_cat' ) ); |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * When a product category is deleted, we need to check |
| 25 | * if the product has no categories assigned. Then assign |
| 26 | * it a default category. We delay this with a scheduled |
| 27 | * action job to not block the response. |
| 28 | * |
| 29 | * @return void |
| 30 | */ |
| 31 | public function schedule_action() { |
| 32 | WC()->queue()->schedule_single( |
| 33 | time(), |
| 34 | 'wc_schedule_update_product_default_cat', |
| 35 | array(), |
| 36 | 'wc_update_product_default_cat' |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Assigns default product category for products |
| 42 | * that have no categories. |
| 43 | * |
| 44 | * @return void |
| 45 | */ |
| 46 | public function maybe_assign_default_product_cat() { |
| 47 | global $wpdb; |
| 48 | |
| 49 | $default_category = get_option( 'default_product_cat', 0 ); |
| 50 | |
| 51 | if ( $default_category ) { |
| 52 | $wpdb->query( |
| 53 | $wpdb->prepare( |
| 54 | "INSERT INTO {$wpdb->term_relationships} (object_id, term_taxonomy_id) |
| 55 | SELECT DISTINCT posts.ID, %s FROM {$wpdb->posts} posts |
| 56 | LEFT JOIN |
| 57 | ( |
| 58 | SELECT object_id FROM {$wpdb->term_relationships} term_relationships |
| 59 | LEFT JOIN {$wpdb->term_taxonomy} term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id |
| 60 | WHERE term_taxonomy.taxonomy = 'product_cat' |
| 61 | ) AS tax_query |
| 62 | ON posts.ID = tax_query.object_id |
| 63 | WHERE posts.post_type = 'product' |
| 64 | AND tax_query.object_id IS NULL", |
| 65 | $default_category |
| 66 | ) |
| 67 | ); |
| 68 | wp_cache_flush(); |
| 69 | delete_transient( 'wc_term_counts' ); |
| 70 | wp_update_term_count_now( array( $default_category ), 'product_cat' ); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 |