| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216 |
- <?php
- /**
- * Category Manipulator class
- *
- * Handles manipulation operations for product categories
- *
- * @since 1.0.0
- * @package Studiou_WC_Product_Cat_Manage
- * @subpackage Studiou_WC_Product_Cat_Manage/includes
- */
- // If this file is called directly, abort.
- if (!defined('WPINC')) {
- die;
- }
- class Studiou_WC_Product_Cat_Manage_Manipulator {
-
- /**
- * Database handler
- *
- * @var Studiou_WC_Product_Cat_Manage_DB
- */
- private $db;
-
- /**
- * Constructor
- *
- * @param Studiou_WC_Product_Cat_Manage_DB $db Database handler
- */
- public function __construct($db) {
- $this->db = $db;
-
- // Register AJAX handlers
- add_action('wp_ajax_studiou_wcpcm_move_products', array($this, 'handle_move_products_ajax'));
- add_action('wp_ajax_studiou_wcpcm_batch_description', array($this, 'handle_batch_description_ajax'));
- add_action('wp_ajax_studiou_wcpcm_delete_products', array($this, 'handle_delete_products_ajax'));
- add_action('wp_ajax_studiou_wcpcm_delete_products_batch', array($this, 'handle_delete_products_batch_ajax'));
- add_action('wp_ajax_studiou_wcpcm_clear_media', array($this, 'handle_clear_media_ajax'));
- add_action('wp_ajax_studiou_wcpcm_clear_media_batch', array($this, 'handle_clear_media_batch_ajax'));
- add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media', array($this, 'handle_remove_unassigned_media_ajax'));
- add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media_batch', array($this, 'handle_remove_unassigned_media_batch_ajax'));
- add_action('wp_ajax_studiou_wcpcm_upvp_get_attributes', array($this, 'handle_upvp_get_attributes_ajax'));
- add_action('wp_ajax_studiou_wcpcm_upvp_get_attribute_values', array($this, 'handle_upvp_get_attribute_values_ajax'));
- add_action('wp_ajax_studiou_wcpcm_upvp_count', array($this, 'handle_upvp_count_ajax'));
- add_action('wp_ajax_studiou_wcpcm_upvp_apply', array($this, 'handle_upvp_apply_ajax'));
- // Tabbed manipulations page - load a tab partial on demand
- add_action('wp_ajax_studiou_wcpcm_load_tab', array($this, 'handle_load_tab_ajax'));
- // Invalidate the cached category/media counts whenever categories or
- // product <-> category relationships change.
- add_action('created_term', array($this, 'bust_count_cache'));
- add_action('edited_term', array($this, 'bust_count_cache'));
- add_action('delete_term', array($this, 'bust_count_cache'));
- add_action('set_object_terms', array($this, 'bust_count_cache'));
- add_action('deleted_term_relationships', array($this, 'bust_count_cache'));
- // Add a test AJAX handler to verify AJAX is working
- add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
- // Debug: Log that the handler is being registered
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
- }
- }
- /**
- * Invalidate the cached category / media-category count data.
- *
- * Hooked to term and term-relationship changes so the counts shown on the
- * manipulations tabs stay accurate.
- */
- public function bust_count_cache() {
- delete_transient('studiou_wcpcm_cat_counts');
- delete_transient('studiou_wcpcm_media_cat_counts');
- }
- /**
- * Handle AJAX request to render a Category Manipulations tab partial.
- *
- * Each tab partial fetches only its own data, so the manipulations page
- * shell can render instantly and heavy calculations run on demand.
- */
- public function handle_load_tab_ajax() {
- // Clean any output buffers to prevent JSON corruption
- while (ob_get_level()) {
- ob_end_clean();
- }
- // Check nonce
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- // Check permissions
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- $tab = isset($_POST['tab']) ? sanitize_key($_POST['tab']) : '';
- $allowed = array('move', 'batch-description', 'delete-products', 'clear-media', 'remove-unassigned', 'upvp', 'notes');
- if (!in_array($tab, $allowed, true)) {
- wp_send_json_error(array(
- 'message' => __('Unknown tab', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- $partial = STUDIOU_WCPCM_PLUGIN_DIR . 'views/manipulations/tab-' . $tab . '.php';
- if (!file_exists($partial)) {
- wp_send_json_error(array(
- 'message' => __('Tab content not found', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- // Made available to the partial; each partial fetches only what it needs.
- $manipulator = $this;
- try {
- ob_start();
- include $partial;
- $html = ob_get_clean();
- wp_send_json_success(array(
- 'tab' => $tab,
- 'html' => $html
- ));
- } catch (Exception $e) {
- if (ob_get_level()) {
- ob_end_clean();
- }
- error_log('STUDIOU WC TABS: tab "' . $tab . '" render failed: ' . $e->getMessage());
- wp_send_json_error(array('message' => $e->getMessage()));
- }
- }
- /**
- * Handle AJAX batch description request
- */
- public function handle_batch_description_ajax() {
- // Clean all output buffers and prevent any output
- while (ob_get_level()) {
- ob_end_clean();
- }
-
- // Start a new output buffer to catch any unwanted output
- ob_start();
-
- // Suppress PHP errors/notices during AJAX to prevent JSON corruption
- $original_error_reporting = error_reporting();
- error_reporting(0);
-
- // Enable error logging only
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Batch description AJAX handler called');
- error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
- }
-
- try {
- // Check nonce
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Check permissions
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Validate input
- if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- }
-
- $selected_categories = array_map('intval', $_POST['selected_categories']);
- $description = sanitize_textarea_field($_POST['description']);
-
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
- error_log('STUDIOU WC: Description: ' . $description);
- }
-
- // Validate categories
- if (empty($selected_categories)) {
- wp_send_json_error(array(
- 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Execute batch description operation
- $result = $this->update_categories_description($selected_categories, $description);
-
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
- error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
- }
-
- // Clean any output that might have been generated
- ob_clean();
-
- // Return success response
- wp_send_json_success(array(
- 'message' => $result['message'],
- 'updated_count' => $result['updated_count'],
- 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
- ));
-
- } catch (Exception $e) {
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
- }
-
- // Clean any output that might have been generated
- ob_clean();
-
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- // Restore original error reporting
- error_reporting($original_error_reporting);
-
- // End the output buffer
- ob_end_clean();
- }
- }
-
- /**
- * Handle AJAX move products request
- */
- public function handle_move_products_ajax() {
- // Clean all output buffers and prevent any output
- while (ob_get_level()) {
- ob_end_clean();
- }
-
- // Start a new output buffer to catch any unwanted output
- ob_start();
-
- // Suppress PHP errors/notices during AJAX to prevent JSON corruption
- $original_error_reporting = error_reporting();
- error_reporting(0);
-
- // Enable error logging only
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: AJAX handler called');
- error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
- }
-
- try {
- // Check nonce
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Check permissions
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Validate input
- if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- }
-
- $source_category_id = intval($_POST['source_category']);
- $target_category_id = intval($_POST['target_category']);
-
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
- }
-
- // Validate categories
- if ($source_category_id === $target_category_id) {
- wp_send_json_error(array(
- 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
- ));
- }
-
- if ($source_category_id <= 0 || $target_category_id <= 0) {
- wp_send_json_error(array(
- 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
- ));
- }
-
- // Execute move operation
- $result = $this->move_products_between_categories($source_category_id, $target_category_id);
-
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
- error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
- }
-
- // Clean any output that might have been generated
- ob_clean();
-
- // Return success response
- wp_send_json_success(array(
- 'message' => $result['message'],
- 'moved_count' => $result['moved_count'],
- 'source_count' => $result['source_count'],
- 'target_count' => $result['target_count'],
- 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
- ));
-
- } catch (Exception $e) {
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
- }
-
- // Clean any output that might have been generated
- ob_clean();
-
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- // Restore original error reporting
- error_reporting($original_error_reporting);
-
- // End the output buffer
- ob_end_clean();
- }
- }
-
- /**
- * Move all products from source category to target category
- *
- * @param int $source_category_id Source category ID
- * @param int $target_category_id Target category ID
- * @return array Result with counts and message
- * @throws Exception On error
- */
- public function move_products_between_categories($source_category_id, $target_category_id) {
- // Get source and target category terms
- $source_category = get_term($source_category_id, 'product_cat');
- $target_category = get_term($target_category_id, 'product_cat');
-
- if (is_wp_error($source_category) || is_wp_error($target_category)) {
- throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
- }
-
- // Get initial count of products in source category using direct DB query
- $initial_source_count = $this->get_category_product_count($source_category_id);
-
- // Check if source category has any products
- if ($initial_source_count === 0) {
- $message = sprintf(
- __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
- $source_category->name
- );
-
- return array(
- 'moved_count' => 0,
- 'source_count' => 0,
- 'target_count' => $this->get_category_product_count($target_category_id),
- 'message' => $message
- );
- }
-
- // Get all products in source category using direct DB query
- $products = $this->get_products_in_category($source_category_id);
- $moved_count = 0;
- $failed_count = 0;
-
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
- }
-
- // Move each product
- foreach ($products as $product_id) {
- // Get current categories for the product
- $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
-
- if (is_wp_error($current_categories)) {
- $failed_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
- }
- continue;
- }
-
- // Remove source category and add target category
- $new_categories = array_diff($current_categories, array($source_category_id));
- $new_categories[] = $target_category_id;
-
- // Update product categories
- $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
-
- if (!is_wp_error($result)) {
- $moved_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
- }
- } else {
- $failed_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
- }
- }
- }
-
- // Get updated counts using direct DB query
- $source_count = $this->get_category_product_count($source_category_id);
- $target_count = $this->get_category_product_count($target_category_id);
-
- // Generate detailed result message
- if ($moved_count === 0 && count($products) > 0) {
- $message = sprintf(
- __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
- $source_category->name,
- $target_category->name,
- count($products)
- );
- } else {
- $message = sprintf(
- __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
- $moved_count,
- $source_category->name,
- $target_category->name,
- $source_count,
- $target_count
- );
-
- if ($failed_count > 0) {
- $message .= ' ' . sprintf(
- __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
- $failed_count
- );
- }
- }
-
- return array(
- 'moved_count' => $moved_count,
- 'source_count' => $source_count,
- 'target_count' => $target_count,
- 'failed_count' => $failed_count,
- 'message' => $message
- );
- }
-
- /**
- * Get product count for a category
- *
- * @param int $category_id Category ID
- * @return int Product count
- */
- private function get_category_product_count($category_id) {
- global $wpdb;
-
- // Use direct database query for more accurate counting
- $sql = "
- SELECT COUNT(DISTINCT p.ID)
- FROM {$wpdb->posts} p
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.term_id = %d
- AND tt.taxonomy = 'product_cat'
- AND p.post_type = 'product'
- AND p.post_status IN ('publish', 'private', 'draft')
- ";
-
- $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
-
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
- }
-
- return intval($count);
- }
-
- /**
- * Get all products in a category
- *
- * @param int $category_id Category ID
- * @return array Array of product IDs
- */
- private function get_products_in_category($category_id) {
- global $wpdb;
-
- // Use direct database query to get products
- $sql = "
- SELECT DISTINCT p.ID
- FROM {$wpdb->posts} p
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.term_id = %d
- AND tt.taxonomy = 'product_cat'
- AND p.post_type = 'product'
- AND p.post_status IN ('publish', 'private', 'draft')
- ";
-
- $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
-
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
- if (!empty($products)) {
- error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
- }
- }
-
- return $products ? array_map('intval', $products) : array();
- }
-
- /**
- * Update descriptions for multiple categories
- *
- * @param array $category_ids Array of category IDs
- * @param string $description New description for categories
- * @return array Result with counts and message
- * @throws Exception On error
- */
- public function update_categories_description($category_ids, $description) {
- $updated_count = 0;
- $failed_count = 0;
- $category_names = array();
-
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
- }
-
- // Update each category
- foreach ($category_ids as $category_id) {
- // Get category term
- $category = get_term($category_id, 'product_cat');
-
- if (is_wp_error($category) || !$category) {
- $failed_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
- }
- continue;
- }
-
- // Update category description
- $result = wp_update_term($category_id, 'product_cat', array(
- 'description' => $description
- ));
-
- if (!is_wp_error($result)) {
- $updated_count++;
- $category_names[] = $category->name;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
- }
- } else {
- $failed_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
- }
- }
- }
-
- // Generate result message
- if ($updated_count === 0) {
- $message = sprintf(
- __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
- $failed_count
- );
- } else {
- $message = sprintf(
- __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
- $updated_count,
- implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
- );
-
- if ($failed_count > 0) {
- $message .= ' ' . sprintf(
- __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
- $failed_count
- );
- }
- }
-
- return array(
- 'updated_count' => $updated_count,
- 'failed_count' => $failed_count,
- 'message' => $message
- );
- }
-
- /**
- * Get all categories with product counts for select lists.
- *
- * Transient-cached wrapper around get_categories_with_counts_uncached().
- * The N+1 per-category count queries are expensive on large stores, so the
- * result is cached for 5 minutes and busted on any category change.
- *
- * @return array Array of categories with ID, name, and product count
- */
- public function get_categories_with_counts() {
- $data = get_transient('studiou_wcpcm_cat_counts');
- if (false === $data) {
- $data = $this->get_categories_with_counts_uncached();
- set_transient('studiou_wcpcm_cat_counts', $data, 5 * MINUTE_IN_SECONDS);
- }
- return $data;
- }
- /**
- * Get all categories with product counts for select lists (uncached).
- *
- * @return array Array of categories with ID, name, and product count
- */
- public function get_categories_with_counts_uncached() {
- $args = array(
- 'taxonomy' => 'product_cat',
- 'orderby' => 'name',
- 'hide_empty' => false,
- );
- $categories = get_terms($args);
- $categories_with_counts = array();
- if (!is_wp_error($categories)) {
- foreach ($categories as $category) {
- $product_count = $this->get_category_product_count($category->term_id);
- $categories_with_counts[] = array(
- 'id' => $category->term_id,
- 'name' => $category->name,
- 'count' => $product_count,
- 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
- );
- }
- }
- return $categories_with_counts;
- }
- /**
- * Handle AJAX delete products request (initial request to get product IDs)
- */
- public function handle_delete_products_ajax() {
- // Clean all output buffers and prevent any output
- while (ob_get_level()) {
- ob_end_clean();
- }
- // Start a new output buffer to catch any unwanted output
- ob_start();
- // Suppress PHP errors/notices during AJAX to prevent JSON corruption
- $original_error_reporting = error_reporting();
- error_reporting(0);
- // Enable error logging only
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Delete products AJAX handler called');
- error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
- }
- try {
- // Check nonce
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- }
- // Check permissions
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- }
- // Validate input
- if (!isset($_POST['delete_categories'])) {
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- }
- $category_ids = array_map('intval', $_POST['delete_categories']);
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
- }
- // Validate categories
- if (empty($category_ids)) {
- wp_send_json_error(array(
- 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
- ));
- }
- // Get all products from selected categories
- $product_ids = $this->get_products_from_categories($category_ids);
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
- }
- // Clean any output that might have been generated
- ob_clean();
- // Return product IDs for batch processing
- wp_send_json_success(array(
- 'product_ids' => $product_ids,
- 'total_count' => count($product_ids),
- 'message' => sprintf(
- __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
- count($product_ids)
- )
- ));
- } catch (Exception $e) {
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
- }
- // Clean any output that might have been generated
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- // Restore original error reporting
- error_reporting($original_error_reporting);
- // End the output buffer
- ob_end_clean();
- }
- }
- /**
- * Handle AJAX delete products batch request (processes products in batches)
- */
- public function handle_delete_products_batch_ajax() {
- // Clean all output buffers and prevent any output
- while (ob_get_level()) {
- ob_end_clean();
- }
- // Start a new output buffer to catch any unwanted output
- ob_start();
- // Suppress PHP errors/notices during AJAX to prevent JSON corruption
- $original_error_reporting = error_reporting();
- error_reporting(0);
- // Enable error logging only
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Delete products batch AJAX handler called');
- error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
- }
- try {
- // Check nonce
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- }
- // Check permissions
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- }
- // Validate input
- if (!isset($_POST['product_ids'])) {
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- }
- $product_ids = array_map('intval', $_POST['product_ids']);
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
- }
- // Delete products in this batch
- $result = $this->delete_products_batch($product_ids);
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
- }
- // Clean any output that might have been generated
- ob_clean();
- // Return success response
- wp_send_json_success(array(
- 'deleted_count' => $result['deleted_count'],
- 'failed_count' => $result['failed_count'],
- 'failed_products' => $result['failed_products']
- ));
- } catch (Exception $e) {
- // Debug logging
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
- }
- // Clean any output that might have been generated
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- // Restore original error reporting
- error_reporting($original_error_reporting);
- // End the output buffer
- ob_end_clean();
- }
- }
- /**
- * Get all products from multiple categories
- *
- * @param array $category_ids Array of category IDs
- * @return array Array of unique product IDs (including parent products with variants)
- */
- private function get_products_from_categories($category_ids) {
- global $wpdb;
- if (empty($category_ids)) {
- return array();
- }
- $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
- // Get all products from selected categories (both simple and parent products)
- $sql = "
- SELECT DISTINCT p.ID
- FROM {$wpdb->posts} p
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.term_id IN ($placeholders)
- AND tt.taxonomy = 'product_cat'
- AND p.post_type = 'product'
- AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
- ";
- $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
- }
- return $products ? array_map('intval', $products) : array();
- }
- /**
- * Delete a batch of products and their variants
- *
- * @param array $product_ids Array of product IDs to delete
- * @return array Result with counts
- */
- private function delete_products_batch($product_ids) {
- $deleted_count = 0;
- $failed_count = 0;
- $failed_products = array();
- foreach ($product_ids as $product_id) {
- try {
- // Get the product object
- $product = wc_get_product($product_id);
- if (!$product) {
- $failed_count++;
- $failed_products[] = $product_id;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Product ' . $product_id . ' not found');
- }
- continue;
- }
- // If it's a variable product, delete all variations first
- if ($product->is_type('variable')) {
- $variations = $product->get_children();
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
- }
- foreach ($variations as $variation_id) {
- $variation = wc_get_product($variation_id);
- if ($variation) {
- $variation->delete(true); // true = force delete permanently
- }
- }
- }
- // Delete the product permanently
- $result = $product->delete(true); // true = force delete permanently
- if ($result) {
- $deleted_count++;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
- }
- } else {
- $failed_count++;
- $failed_products[] = $product_id;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Failed to delete product ' . $product_id);
- }
- }
- } catch (Exception $e) {
- $failed_count++;
- $failed_products[] = $product_id;
- if (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
- }
- }
- }
- return array(
- 'deleted_count' => $deleted_count,
- 'failed_count' => $failed_count,
- 'failed_products' => $failed_products
- );
- }
- /**
- * Get all media categories with file counts for select lists.
- *
- * Transient-cached wrapper around get_media_categories_with_counts_uncached().
- *
- * @return array Array of media categories with ID, name, and file count
- */
- public function get_media_categories_with_counts() {
- $data = get_transient('studiou_wcpcm_media_cat_counts');
- if (false === $data) {
- $data = $this->get_media_categories_with_counts_uncached();
- set_transient('studiou_wcpcm_media_cat_counts', $data, 5 * MINUTE_IN_SECONDS);
- }
- return $data;
- }
- /**
- * Get all media categories with file counts for select lists (uncached).
- *
- * @return array Array of media categories with ID, name, and file count
- */
- public function get_media_categories_with_counts_uncached() {
- $taxonomy = $this->get_media_category_taxonomy();
- if (!$taxonomy) {
- return array();
- }
- $args = array(
- 'taxonomy' => $taxonomy,
- 'orderby' => 'name',
- 'hide_empty' => false,
- );
- $categories = get_terms($args);
- $categories_with_counts = array();
- if (!is_wp_error($categories)) {
- foreach ($categories as $category) {
- $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
- $categories_with_counts[] = array(
- 'id' => $category->term_id,
- 'name' => $category->name,
- 'count' => $file_count,
- 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
- );
- }
- }
- return $categories_with_counts;
- }
- /**
- * Get the media category taxonomy name
- *
- * Checks for common media category taxonomies used by popular plugins
- *
- * @return string|false Taxonomy name or false if none found
- */
- private function get_media_category_taxonomy() {
- $possible_taxonomies = array(
- 'media_category',
- 'attachment_category',
- 'media-category',
- );
- foreach ($possible_taxonomies as $taxonomy) {
- if (taxonomy_exists($taxonomy)) {
- error_log('STUDIOU WC MEDIA: Detected media taxonomy: ' . $taxonomy);
- return $taxonomy;
- }
- }
- // Try to find any taxonomy registered for attachments
- $attachment_taxonomies = get_object_taxonomies('attachment', 'names');
- if (!empty($attachment_taxonomies)) {
- // Filter out built-in taxonomies
- $custom_taxonomies = array_filter($attachment_taxonomies, function($tax) {
- return !in_array($tax, array('post_tag', 'category', 'post_format'));
- });
- if (!empty($custom_taxonomies)) {
- $found = reset($custom_taxonomies);
- error_log('STUDIOU WC MEDIA: Auto-detected attachment taxonomy: ' . $found);
- return $found;
- }
- }
- error_log('STUDIOU WC MEDIA: No media category taxonomy found. Registered attachment taxonomies: ' . implode(', ', $attachment_taxonomies ?? array()));
- return false;
- }
- /**
- * Get file count for a media category
- *
- * @param int $category_id Category term ID
- * @param string $taxonomy Taxonomy name
- * @return int File count
- */
- private function get_media_category_file_count($category_id, $taxonomy) {
- global $wpdb;
- $sql = "
- SELECT COUNT(DISTINCT p.ID)
- FROM {$wpdb->posts} p
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.term_id = %d
- AND tt.taxonomy = %s
- AND p.post_type = 'attachment'
- ";
- $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
- return intval($count);
- }
- /**
- * Get all media IDs from multiple media categories
- *
- * @param array $category_ids Array of category term IDs
- * @return array Array of unique attachment IDs
- */
- private function get_media_from_categories($category_ids) {
- global $wpdb;
- $taxonomy = $this->get_media_category_taxonomy();
- error_log('STUDIOU WC MEDIA: get_media_from_categories called - taxonomy: ' . ($taxonomy ?: 'false') . ', category_ids: ' . implode(', ', $category_ids));
- if (!$taxonomy || empty($category_ids)) {
- error_log('STUDIOU WC MEDIA: No taxonomy or empty category_ids, returning empty');
- return array();
- }
- $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
- $sql = "
- SELECT DISTINCT p.ID
- FROM {$wpdb->posts} p
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.term_id IN ($placeholders)
- AND tt.taxonomy = %s
- AND p.post_type = 'attachment'
- ";
- $params = array_merge($category_ids, array($taxonomy));
- $media = $wpdb->get_col($wpdb->prepare($sql, ...$params));
- error_log('STUDIOU WC MEDIA: Query found ' . ($media ? count($media) : 0) . ' media files');
- return $media ? array_map('intval', $media) : array();
- }
- /**
- * Delete a batch of media files permanently
- *
- * @param array $media_ids Array of attachment IDs to delete
- * @return array Result with counts
- */
- private function delete_media_batch($media_ids) {
- global $wpdb;
- $deleted_count = 0;
- $failed_count = 0;
- $failed_media = array();
- $affected_term_ids = array();
- $taxonomy = $this->get_media_category_taxonomy();
- // Ensure required file functions are loaded
- if (!function_exists('wp_delete_attachment')) {
- require_once ABSPATH . 'wp-admin/includes/post.php';
- }
- if (!function_exists('wp_delete_file')) {
- require_once ABSPATH . 'wp-includes/functions.php';
- }
- error_log('STUDIOU WC MEDIA: delete_media_batch called with ' . count($media_ids) . ' media IDs');
- foreach ($media_ids as $media_id) {
- try {
- $attachment = get_post($media_id);
- if (!$attachment || $attachment->post_type !== 'attachment') {
- $failed_count++;
- $failed_media[] = $media_id;
- error_log('STUDIOU WC MEDIA: Media file ' . $media_id . ' not found or not an attachment');
- continue;
- }
- // Collect affected term IDs before deletion for count update
- if ($taxonomy) {
- $terms = wp_get_object_terms($media_id, $taxonomy, array('fields' => 'ids'));
- if (!is_wp_error($terms)) {
- $affected_term_ids = array_merge($affected_term_ids, $terms);
- }
- }
- // Get file paths BEFORE deletion
- $file = get_attached_file($media_id);
- $meta = wp_get_attachment_metadata($media_id);
- $upload_dir = wp_get_upload_dir();
- error_log('STUDIOU WC MEDIA: Deleting media ID ' . $media_id . ', file: ' . ($file ?: 'none'));
- // Attempt standard WordPress deletion
- wp_delete_attachment($media_id, true);
- // Verify the post was actually deleted
- $still_exists = $wpdb->get_var($wpdb->prepare(
- "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
- $media_id
- ));
- if ($still_exists) {
- error_log('STUDIOU WC MEDIA: wp_delete_attachment did not delete post ' . $media_id . ', forcing manual deletion');
- // Force manual deletion: remove term relationships
- $all_taxonomies = get_object_taxonomies('attachment');
- if (!empty($all_taxonomies)) {
- wp_delete_object_term_relationships($media_id, $all_taxonomies);
- }
- // Remove all post meta
- $wpdb->delete($wpdb->postmeta, array('post_id' => $media_id));
- // Remove the post itself
- $wpdb->delete($wpdb->posts, array('ID' => $media_id));
- // Clean cache
- clean_post_cache($media_id);
- }
- // Delete physical files from disk
- if ($file && file_exists($file)) {
- @unlink($file);
- error_log('STUDIOU WC MEDIA: Deleted main file: ' . $file);
- }
- // Delete thumbnail/intermediate sizes
- if (!empty($meta['sizes']) && !empty($upload_dir['basedir'])) {
- $file_dir = !empty($file) ? trailingslashit(dirname($file)) : '';
- foreach ($meta['sizes'] as $size => $sizeinfo) {
- if (!empty($sizeinfo['file'])) {
- $intermediate_file = $file_dir . $sizeinfo['file'];
- if (file_exists($intermediate_file)) {
- @unlink($intermediate_file);
- }
- }
- }
- }
- // Final verification
- $final_check = $wpdb->get_var($wpdb->prepare(
- "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
- $media_id
- ));
- if (!$final_check) {
- $deleted_count++;
- error_log('STUDIOU WC MEDIA: Successfully deleted media file ' . $media_id);
- } else {
- $failed_count++;
- $failed_media[] = $media_id;
- error_log('STUDIOU WC MEDIA: FAILED to delete media file ' . $media_id . ' even after manual cleanup');
- }
- } catch (Exception $e) {
- $failed_count++;
- $failed_media[] = $media_id;
- error_log('STUDIOU WC MEDIA: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
- }
- }
- // Force update term counts for affected categories
- if ($taxonomy && !empty($affected_term_ids)) {
- $affected_term_ids = array_unique($affected_term_ids);
- wp_update_term_count_now($affected_term_ids, $taxonomy);
- error_log('STUDIOU WC MEDIA: Updated term counts for term IDs: ' . implode(', ', $affected_term_ids));
- }
- error_log('STUDIOU WC MEDIA: Batch result - deleted: ' . $deleted_count . ', failed: ' . $failed_count);
- return array(
- 'deleted_count' => $deleted_count,
- 'failed_count' => $failed_count,
- 'failed_media' => $failed_media
- );
- }
- /**
- * Handle AJAX clear media request (initial request to get media IDs)
- */
- public function handle_clear_media_ajax() {
- while (ob_get_level()) {
- ob_end_clean();
- }
- ob_start();
- $original_error_reporting = error_reporting();
- error_reporting(0);
- error_log('STUDIOU WC MEDIA: Clear media AJAX handler called');
- error_log('STUDIOU WC MEDIA: POST data: ' . print_r($_POST, true));
- try {
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- error_log('STUDIOU WC MEDIA: Nonce verification failed');
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- if (!current_user_can('manage_woocommerce')) {
- error_log('STUDIOU WC MEDIA: Permission check failed');
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- if (!isset($_POST['media_categories'])) {
- error_log('STUDIOU WC MEDIA: media_categories not in POST data');
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- $category_ids = array_map('intval', $_POST['media_categories']);
- if (empty($category_ids)) {
- error_log('STUDIOU WC MEDIA: Empty category_ids after intval mapping');
- wp_send_json_error(array(
- 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- $media_ids = $this->get_media_from_categories($category_ids);
- error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' media files to delete from categories: ' . implode(', ', $category_ids));
- ob_clean();
- wp_send_json_success(array(
- 'media_ids' => $media_ids,
- 'total_count' => count($media_ids),
- 'message' => sprintf(
- __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
- count($media_ids)
- )
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC MEDIA: Clear media operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * Handle AJAX clear media batch request (processes media in batches)
- */
- public function handle_clear_media_batch_ajax() {
- while (ob_get_level()) {
- ob_end_clean();
- }
- ob_start();
- $original_error_reporting = error_reporting();
- error_reporting(0);
- error_log('STUDIOU WC MEDIA: Clear media batch AJAX handler called');
- try {
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- error_log('STUDIOU WC MEDIA: Batch nonce verification failed');
- wp_send_json_error(array(
- 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- if (!current_user_can('manage_woocommerce')) {
- error_log('STUDIOU WC MEDIA: Batch permission check failed');
- wp_send_json_error(array(
- 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- if (!isset($_POST['media_ids'])) {
- error_log('STUDIOU WC MEDIA: media_ids not in POST data');
- wp_send_json_error(array(
- 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
- ));
- return;
- }
- $media_ids = array_map('intval', $_POST['media_ids']);
- error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' media files for deletion');
- $result = $this->delete_media_batch($media_ids);
- error_log('STUDIOU WC MEDIA: Batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
- ob_clean();
- wp_send_json_success(array(
- 'deleted_count' => $result['deleted_count'],
- 'failed_count' => $result['failed_count'],
- 'failed_media' => $result['failed_media']
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC MEDIA: Clear media batch operation failed - ' . $e->getMessage());
- error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(
- __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
- $e->getMessage()
- )
- ));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * Get count of unassigned unused media files
- *
- * @return int Count of media files not in any category and not referenced
- */
- public function get_unassigned_unused_media_count() {
- $ids = $this->get_unassigned_unused_media_ids();
- return count($ids);
- }
- /**
- * Get IDs of media files that are not assigned to any media category
- * and not used as featured image, product gallery image, or attached to any post.
- *
- * @return array Array of attachment IDs
- */
- public function get_unassigned_unused_media_ids() {
- global $wpdb;
- $taxonomy = $this->get_media_category_taxonomy();
- // Base query: all attachments not used as featured image and not attached to a post
- $sql = "
- SELECT a.ID
- FROM {$wpdb->posts} a
- LEFT JOIN {$wpdb->postmeta} pm_thumb
- ON a.ID = CAST(pm_thumb.meta_value AS UNSIGNED)
- AND pm_thumb.meta_key = '_thumbnail_id'
- WHERE a.post_type = 'attachment'
- AND a.post_parent = 0
- AND pm_thumb.meta_id IS NULL
- ";
- // If media category taxonomy exists, also exclude categorized media
- if ($taxonomy) {
- $sql .= $wpdb->prepare("
- AND a.ID NOT IN (
- SELECT tr.object_id
- FROM {$wpdb->term_relationships} tr
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE tt.taxonomy = %s
- )
- ", $taxonomy);
- }
- $media_ids = $wpdb->get_col($sql);
- if (empty($media_ids)) {
- return array();
- }
- $media_ids = array_map('intval', $media_ids);
- // Filter out media used in WooCommerce product galleries (_product_image_gallery)
- $gallery_meta = $wpdb->get_col(
- "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value != ''"
- );
- if (!empty($gallery_meta)) {
- $gallery_ids = array();
- foreach ($gallery_meta as $gallery_value) {
- $ids = array_map('intval', array_filter(explode(',', $gallery_value)));
- $gallery_ids = array_merge($gallery_ids, $ids);
- }
- $gallery_ids = array_unique($gallery_ids);
- if (!empty($gallery_ids)) {
- $media_ids = array_diff($media_ids, $gallery_ids);
- }
- }
- error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files');
- return array_values($media_ids);
- }
- /**
- * Handle AJAX remove unassigned media request (get IDs)
- */
- public function handle_remove_unassigned_media_ajax() {
- while (ob_get_level()) {
- ob_end_clean();
- }
- ob_start();
- $original_error_reporting = error_reporting();
- error_reporting(0);
- error_log('STUDIOU WC MEDIA: Remove unassigned media AJAX handler called');
- try {
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
- return;
- }
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
- return;
- }
- $media_ids = $this->get_unassigned_unused_media_ids();
- error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files to delete');
- ob_clean();
- wp_send_json_success(array(
- 'media_ids' => $media_ids,
- 'total_count' => count($media_ids),
- 'message' => sprintf(
- __('Found %d unused uncategorized media files to delete', 'studiou-wc-product-cat-manage'),
- count($media_ids)
- )
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC MEDIA: Remove unassigned media failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
- ));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * Handle AJAX remove unassigned media batch request
- */
- public function handle_remove_unassigned_media_batch_ajax() {
- while (ob_get_level()) {
- ob_end_clean();
- }
- ob_start();
- $original_error_reporting = error_reporting();
- error_reporting(0);
- error_log('STUDIOU WC MEDIA: Remove unassigned media batch AJAX handler called');
- try {
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
- return;
- }
- if (!current_user_can('manage_woocommerce')) {
- wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
- return;
- }
- if (!isset($_POST['media_ids'])) {
- wp_send_json_error(array('message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')));
- return;
- }
- $media_ids = array_map('intval', $_POST['media_ids']);
- error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' unassigned media for deletion');
- $result = $this->delete_media_batch($media_ids);
- error_log('STUDIOU WC MEDIA: Unassigned batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
- ob_clean();
- wp_send_json_success(array(
- 'deleted_count' => $result['deleted_count'],
- 'failed_count' => $result['failed_count'],
- 'failed_media' => $result['failed_media']
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC MEDIA: Unassigned media batch failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array(
- 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
- ));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- // ========================================================================
- // Update Product Variant Prices (UPVP) — v1.5.3
- // Bulk-update regular_price on product_variation records by category +
- // attribute filter. Touches only product records; never order items, carts,
- // or historical order data.
- // ========================================================================
- /**
- * Get list of attribute "heads" usable for variations.
- *
- * Source 1: every wc_get_attribute_taxonomies() entry (global attributes)
- * — key = 'pa_<slug>', is_taxonomy = true.
- * Source 2: distinct meta_key starting with 'attribute_' on product_variation
- * rows that are NOT global taxonomies (custom product-level
- * attributes flagged for variations) — key = '<slug>',
- * is_taxonomy = false.
- *
- * @return array [ ['key' => string, 'label' => string, 'is_taxonomy' => bool], ... ]
- */
- public function get_variation_attribute_heads() {
- global $wpdb;
- $heads = array();
- $seen = array();
- // Source 1: global taxonomies.
- $taxonomies = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : array();
- if (!empty($taxonomies)) {
- foreach ($taxonomies as $tax) {
- $key = 'pa_' . $tax->attribute_name;
- if (isset($seen[$key])) {
- continue;
- }
- $seen[$key] = true;
- $heads[] = array(
- 'key' => $key,
- 'label' => !empty($tax->attribute_label) ? $tax->attribute_label : $tax->attribute_name,
- 'is_taxonomy' => true,
- );
- }
- }
- // Source 2: existing variation postmeta (attribute_*).
- $sql = "
- SELECT DISTINCT pm.meta_key
- FROM {$wpdb->postmeta} pm
- INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
- WHERE v.post_type = 'product_variation'
- AND v.post_status IN ('publish','private')
- AND pm.meta_key LIKE %s
- ";
- $rows = $wpdb->get_col($wpdb->prepare($sql, $wpdb->esc_like('attribute_') . '%'));
- if (!empty($rows)) {
- foreach ($rows as $meta_key) {
- $slug = substr($meta_key, strlen('attribute_'));
- if ($slug === '' || isset($seen[$slug])) {
- continue;
- }
- $seen[$slug] = true;
- $heads[] = array(
- 'key' => $slug,
- 'label' => wc_attribute_label($slug),
- 'is_taxonomy' => (strpos($slug, 'pa_') === 0) || taxonomy_exists($slug),
- );
- }
- }
- // Source 3: variable parent products' _product_attributes postmeta.
- // Catches attributes flagged "Used for variations" on the product's
- // Attributes tab, even when (a) the attribute is a custom non-global
- // entry, or (b) no variations have been generated yet.
- $sql_parents = "
- SELECT pm.meta_value
- FROM {$wpdb->postmeta} pm
- INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
- WHERE p.post_type = 'product'
- AND p.post_status IN ('publish','private','draft')
- AND pm.meta_key = '_product_attributes'
- ";
- $serialized_rows = $wpdb->get_col($sql_parents);
- if (!empty($serialized_rows)) {
- foreach ($serialized_rows as $serialized) {
- $attrs = maybe_unserialize($serialized);
- if (!is_array($attrs)) {
- continue;
- }
- foreach ($attrs as $attr_key => $attr_data) {
- if (!is_array($attr_data) || empty($attr_data['is_variation'])) {
- continue;
- }
- $is_taxonomy = !empty($attr_data['is_taxonomy']);
- $name = isset($attr_data['name']) ? $attr_data['name'] : $attr_key;
- $key = $is_taxonomy ? $name : sanitize_title($name);
- if ($key === '' || isset($seen[$key])) {
- continue;
- }
- $seen[$key] = true;
- $heads[] = array(
- 'key' => $key,
- 'label' => $is_taxonomy ? wc_attribute_label($key) : $name,
- 'is_taxonomy' => $is_taxonomy,
- );
- }
- }
- }
- // Sort alphabetically by label.
- usort($heads, function($a, $b) {
- return strcasecmp($a['label'], $b['label']);
- });
- return $heads;
- }
- /**
- * Get distinct values for the given attribute key, scoped to existing
- * variations (and optionally to a set of parent product categories).
- *
- * For taxonomy attributes (pa_*) the meta_value is the term slug; we
- * resolve labels via get_term_by('slug', ..., $taxonomy).
- *
- * @param string $attribute_key E.g. 'pa_color' or 'size'.
- * @param int[] $category_ids Optional list of parent product_cat term IDs.
- * @return array [ ['value' => string, 'label' => string], ... ]
- */
- public function get_variation_attribute_values($attribute_key, $category_ids = array()) {
- global $wpdb;
- $attribute_key = sanitize_text_field($attribute_key);
- if ($attribute_key === '') {
- return array();
- }
- $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
- $params = array($meta_key);
- $cat_join = '';
- $cat_where = '';
- if (!empty($category_ids)) {
- $cat_ids = array_map('intval', $category_ids);
- $cat_ids = array_filter($cat_ids, function($v) { return $v > 0; });
- if (!empty($cat_ids)) {
- $placeholders = implode(',', array_fill(0, count($cat_ids), '%d'));
- $cat_join = "
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- ";
- $cat_where = "
- AND tt.taxonomy = 'product_cat'
- AND tt.term_id IN ($placeholders)
- ";
- $params = array_merge($params, $cat_ids);
- }
- }
- $sql = "
- SELECT DISTINCT pm.meta_value
- FROM {$wpdb->postmeta} pm
- INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
- AND v.post_type = 'product_variation'
- AND v.post_status IN ('publish','private')
- INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
- AND p.post_type = 'product'
- $cat_join
- WHERE pm.meta_key = %s
- AND pm.meta_value <> ''
- $cat_where
- ";
- $values = $wpdb->get_col($wpdb->prepare($sql, ...$params));
- $is_taxonomy = (strpos($attribute_key, 'pa_') === 0) || taxonomy_exists($attribute_key);
- // Fallback: if SQL returned no values but the attribute exists on a
- // variable parent's _product_attributes (e.g. variations not generated
- // yet, or custom attribute), parse pipe-separated values from there.
- if (empty($values)) {
- $sanitized_key = $is_taxonomy
- ? (strpos($attribute_key, 'pa_') === 0 ? $attribute_key : 'pa_' . $attribute_key)
- : sanitize_title($attribute_key);
- $sql_parents = "
- SELECT pm.meta_value
- FROM {$wpdb->postmeta} pm
- INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
- WHERE p.post_type = 'product'
- AND p.post_status IN ('publish','private','draft')
- AND pm.meta_key = '_product_attributes'
- ";
- $rows = $wpdb->get_col($sql_parents);
- $values = array();
- if (!empty($rows)) {
- foreach ($rows as $serialized) {
- $attrs = maybe_unserialize($serialized);
- if (!is_array($attrs) || !isset($attrs[$sanitized_key])) {
- continue;
- }
- $entry = $attrs[$sanitized_key];
- if (empty($entry['is_variation'])) {
- continue;
- }
- if ($is_taxonomy) {
- // Taxonomy custom values are stored as term IDs in 'value'.
- $term_ids = !empty($entry['value']) ? wp_parse_id_list($entry['value']) : array();
- if (empty($term_ids)) {
- // Or the parent uses all terms — pull them from the taxonomy.
- $tax_name = $sanitized_key;
- $terms = get_terms(array('taxonomy' => $tax_name, 'hide_empty' => false));
- if (!is_wp_error($terms)) {
- foreach ($terms as $t) {
- $values[] = $t->slug;
- }
- }
- } else {
- foreach ($term_ids as $tid) {
- $term = get_term($tid, $sanitized_key);
- if ($term && !is_wp_error($term)) {
- $values[] = $term->slug;
- }
- }
- }
- } else {
- $raw = isset($entry['value']) ? (string) $entry['value'] : '';
- if ($raw !== '') {
- $parts = array_map('trim', explode('|', $raw));
- foreach ($parts as $p) {
- if ($p !== '') {
- $values[] = $p;
- }
- }
- }
- }
- }
- $values = array_values(array_unique($values));
- }
- }
- if (empty($values)) {
- return array();
- }
- $result = array();
- foreach ($values as $value) {
- $label = $value;
- if ($is_taxonomy) {
- $tax = (strpos($attribute_key, 'pa_') === 0) ? $attribute_key : 'pa_' . $attribute_key;
- $term = get_term_by('slug', $value, $tax);
- if ($term && !is_wp_error($term)) {
- $label = $term->name;
- }
- }
- $result[] = array(
- 'value' => $value,
- 'label' => $label,
- );
- }
- usort($result, function($a, $b) {
- return strcasecmp($a['label'], $b['label']);
- });
- return $result;
- }
- /**
- * Find variations matching the filter.
- *
- * @param int[] $category_ids
- * @param string $attribute_key
- * @param string $attribute_value
- * @return array ['count' => int, 'ids' => int[], 'sample' => array[]]
- */
- public function find_matching_variations($category_ids, $attribute_key, $attribute_value) {
- global $wpdb;
- $category_ids = array_filter(array_map('intval', (array) $category_ids), function($v) { return $v > 0; });
- $attribute_key = sanitize_text_field($attribute_key);
- $attribute_value = sanitize_text_field($attribute_value);
- if (empty($category_ids) || $attribute_key === '' || $attribute_value === '') {
- return array('count' => 0, 'ids' => array(), 'sample' => array());
- }
- $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
- $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
- $sql = "
- SELECT DISTINCT v.ID
- FROM {$wpdb->posts} v
- INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
- INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = v.ID
- INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
- INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
- WHERE v.post_type = 'product_variation'
- AND v.post_status IN ('publish','private')
- AND p.post_type = 'product'
- AND tt.taxonomy = 'product_cat'
- AND tt.term_id IN ($placeholders)
- AND pm.meta_key = %s
- AND pm.meta_value = %s
- ";
- $params = array_merge($category_ids, array($meta_key, $attribute_value));
- $ids = $wpdb->get_col($wpdb->prepare($sql, ...$params));
- $ids = $ids ? array_map('intval', $ids) : array();
- // Build a sample (up to 20).
- $sample = array();
- $slice = array_slice($ids, 0, 20);
- foreach ($slice as $id) {
- $variation = wc_get_product($id);
- if (!$variation) {
- continue;
- }
- $parent_id = $variation->get_parent_id();
- $parent_name = '';
- if ($parent_id) {
- $parent = wc_get_product($parent_id);
- if ($parent) {
- $parent_name = $parent->get_name();
- }
- }
- $sample[] = array(
- 'id' => $id,
- 'sku' => $variation->get_sku(),
- 'name' => $variation->get_name(),
- 'parent_name' => $parent_name,
- 'current_price' => $variation->get_regular_price(),
- );
- }
- return array(
- 'count' => count($ids),
- 'ids' => $ids,
- 'sample' => $sample,
- );
- }
- /**
- * Apply new regular price to a list of variation IDs.
- *
- * @param int[] $variation_ids
- * @param string $new_price
- * @return array ['updated','failed','failed_ids','message']
- */
- public function apply_variant_price($variation_ids, $new_price) {
- $variation_ids = array_filter(array_map('intval', (array) $variation_ids), function($v) { return $v > 0; });
- // Validate price.
- if (!is_numeric($new_price) || (float) $new_price < 0) {
- return array(
- 'updated' => 0,
- 'failed' => 0,
- 'failed_ids' => array(),
- 'message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage'),
- 'error' => true,
- );
- }
- $formatted = wc_format_decimal($new_price);
- $updated = 0;
- $failed = 0;
- $failed_ids = array();
- $parent_ids = array();
- foreach ($variation_ids as $id) {
- try {
- $variation = wc_get_product($id);
- if (!$variation || !$variation->is_type('variation')) {
- $failed++;
- $failed_ids[] = $id;
- error_log('STUDIOU WC UPVP: Variation ' . $id . ' not found or not a variation');
- continue;
- }
- $variation->set_regular_price($formatted);
- $variation->save();
- $updated++;
- $parent_id = $variation->get_parent_id();
- if ($parent_id) {
- $parent_ids[$parent_id] = true;
- }
- } catch (Exception $e) {
- $failed++;
- $failed_ids[] = $id;
- error_log('STUDIOU WC UPVP: Exception updating variation ' . $id . ' - ' . $e->getMessage());
- }
- }
- // Re-sync parent variable products so price-range cache reflects the new prices.
- if (!empty($parent_ids) && class_exists('WC_Product_Variable')) {
- foreach (array_keys($parent_ids) as $parent_id) {
- try {
- WC_Product_Variable::sync($parent_id);
- if (function_exists('wc_delete_product_transients')) {
- wc_delete_product_transients($parent_id);
- }
- } catch (Exception $e) {
- error_log('STUDIOU WC UPVP: Failed to sync parent ' . $parent_id . ' - ' . $e->getMessage());
- }
- }
- }
- $message = sprintf(
- __('Successfully updated %d variations.', 'studiou-wc-product-cat-manage'),
- $updated
- );
- if ($failed > 0) {
- $message .= ' ' . sprintf(
- __('Failed to update %d variations.', 'studiou-wc-product-cat-manage'),
- $failed
- );
- }
- return array(
- 'updated' => $updated,
- 'failed' => $failed,
- 'failed_ids' => $failed_ids,
- 'message' => $message,
- );
- }
- /**
- * Common AJAX preflight: nonce + capability + output buffer setup.
- * Returns false on failure (after sending JSON error), true on success.
- */
- private function upvp_preflight() {
- while (ob_get_level()) {
- ob_end_clean();
- }
- ob_start();
- if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
- ob_clean();
- wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
- return false;
- }
- if (!current_user_can('manage_woocommerce')) {
- ob_clean();
- wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
- return false;
- }
- return true;
- }
- /**
- * AJAX: list variation attribute heads.
- */
- public function handle_upvp_get_attributes_ajax() {
- if (!$this->upvp_preflight()) return;
- $original_error_reporting = error_reporting();
- error_reporting(0);
- try {
- $heads = $this->get_variation_attribute_heads();
- ob_clean();
- wp_send_json_success(array('attributes' => $heads));
- } catch (Exception $e) {
- error_log('STUDIOU WC UPVP: get_attributes failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array('message' => $e->getMessage()));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * AJAX: list values for the chosen attribute (scoped to selected categories).
- */
- public function handle_upvp_get_attribute_values_ajax() {
- if (!$this->upvp_preflight()) return;
- $original_error_reporting = error_reporting();
- error_reporting(0);
- try {
- $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
- $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
- if ($attribute_key === '') {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
- return;
- }
- $values = $this->get_variation_attribute_values($attribute_key, $category_ids);
- ob_clean();
- wp_send_json_success(array('values' => $values));
- } catch (Exception $e) {
- error_log('STUDIOU WC UPVP: get_attribute_values failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array('message' => $e->getMessage()));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * AJAX: count + sample of variations matching the current filter.
- */
- public function handle_upvp_count_ajax() {
- if (!$this->upvp_preflight()) return;
- $original_error_reporting = error_reporting();
- error_reporting(0);
- try {
- $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
- $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
- $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
- if (empty($category_ids)) {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
- return;
- }
- if ($attribute_key === '') {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
- return;
- }
- if ($attribute_value === '') {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
- return;
- }
- $result = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
- ob_clean();
- wp_send_json_success(array(
- 'count' => $result['count'],
- 'sample' => $result['sample'],
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC UPVP: count failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array('message' => $e->getMessage()));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- /**
- * AJAX: apply new regular price to all matching variations.
- */
- public function handle_upvp_apply_ajax() {
- if (!$this->upvp_preflight()) return;
- $original_error_reporting = error_reporting();
- error_reporting(0);
- try {
- $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
- $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
- $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
- $new_price = isset($_POST['new_price']) ? sanitize_text_field(wp_unslash($_POST['new_price'])) : '';
- if (empty($category_ids)) {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
- return;
- }
- if ($attribute_key === '' || $attribute_value === '') {
- ob_clean();
- wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
- return;
- }
- if ($new_price === '' || !is_numeric($new_price) || (float) $new_price < 0) {
- ob_clean();
- wp_send_json_error(array('message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage')));
- return;
- }
- $matching = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
- if ($matching['count'] === 0) {
- ob_clean();
- wp_send_json_error(array('message' => __('No variations match the current filter.', 'studiou-wc-product-cat-manage')));
- return;
- }
- $result = $this->apply_variant_price($matching['ids'], $new_price);
- ob_clean();
- wp_send_json_success(array(
- 'updated' => $result['updated'],
- 'failed' => $result['failed'],
- 'failed_ids' => $result['failed_ids'],
- 'message' => $result['message'],
- ));
- } catch (Exception $e) {
- error_log('STUDIOU WC UPVP: apply failed - ' . $e->getMessage());
- ob_clean();
- wp_send_json_error(array('message' => $e->getMessage()));
- } finally {
- error_reporting($original_error_reporting);
- ob_end_clean();
- }
- }
- }
|