class-studiou-wc-product-cat-manage-manipulator.php 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. <?php
  2. /**
  3. * Category Manipulator class
  4. *
  5. * Handles manipulation operations for product categories
  6. *
  7. * @since 1.0.0
  8. * @package Studiou_WC_Product_Cat_Manage
  9. * @subpackage Studiou_WC_Product_Cat_Manage/includes
  10. */
  11. // If this file is called directly, abort.
  12. if (!defined('WPINC')) {
  13. die;
  14. }
  15. class Studiou_WC_Product_Cat_Manage_Manipulator {
  16. /**
  17. * Database handler
  18. *
  19. * @var Studiou_WC_Product_Cat_Manage_DB
  20. */
  21. private $db;
  22. /**
  23. * Constructor
  24. *
  25. * @param Studiou_WC_Product_Cat_Manage_DB $db Database handler
  26. */
  27. public function __construct($db) {
  28. $this->db = $db;
  29. // Register AJAX handlers
  30. // Legacy single-shot move (v1.0+). Kept for back-compat; JS now uses
  31. // the batched flow added in v1.7.0.
  32. add_action('wp_ajax_studiou_wcpcm_move_products', array($this, 'handle_move_products_ajax'));
  33. // v1.7.0 — M2: batched product move. Mirrors the delete-products
  34. // pattern: start returns the list of product IDs in the source
  35. // category; chunk processes 25 IDs per AJAX call. Removes the
  36. // single-shot timeout on large source categories.
  37. add_action('wp_ajax_studiou_wcpcm_move_products_start', array($this, 'handle_move_products_start_ajax'));
  38. add_action('wp_ajax_studiou_wcpcm_move_products_chunk', array($this, 'handle_move_products_chunk_ajax'));
  39. add_action('wp_ajax_studiou_wcpcm_batch_description', array($this, 'handle_batch_description_ajax'));
  40. add_action('wp_ajax_studiou_wcpcm_delete_products', array($this, 'handle_delete_products_ajax'));
  41. add_action('wp_ajax_studiou_wcpcm_delete_products_batch', array($this, 'handle_delete_products_batch_ajax'));
  42. add_action('wp_ajax_studiou_wcpcm_clear_media', array($this, 'handle_clear_media_ajax'));
  43. add_action('wp_ajax_studiou_wcpcm_clear_media_batch', array($this, 'handle_clear_media_batch_ajax'));
  44. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media', array($this, 'handle_remove_unassigned_media_ajax'));
  45. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media_batch', array($this, 'handle_remove_unassigned_media_batch_ajax'));
  46. add_action('wp_ajax_studiou_wcpcm_upvp_get_attributes', array($this, 'handle_upvp_get_attributes_ajax'));
  47. add_action('wp_ajax_studiou_wcpcm_upvp_get_attribute_values', array($this, 'handle_upvp_get_attribute_values_ajax'));
  48. add_action('wp_ajax_studiou_wcpcm_upvp_count', array($this, 'handle_upvp_count_ajax'));
  49. add_action('wp_ajax_studiou_wcpcm_upvp_apply', array($this, 'handle_upvp_apply_ajax'));
  50. // Tabbed manipulations page - load a tab partial on demand
  51. add_action('wp_ajax_studiou_wcpcm_load_tab', array($this, 'handle_load_tab_ajax'));
  52. // Invalidate the cached category/media counts whenever categories or
  53. // product <-> category relationships change.
  54. add_action('created_term', array($this, 'bust_count_cache'));
  55. add_action('edited_term', array($this, 'bust_count_cache'));
  56. add_action('delete_term', array($this, 'bust_count_cache'));
  57. add_action('set_object_terms', array($this, 'bust_count_cache'));
  58. add_action('deleted_term_relationships', array($this, 'bust_count_cache'));
  59. // Add a test AJAX handler to verify AJAX is working
  60. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  61. // Debug: Log that the handler is being registered
  62. if (defined('WP_DEBUG') && WP_DEBUG) {
  63. error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
  64. }
  65. }
  66. /**
  67. * Invalidate the cached category / media-category count data.
  68. *
  69. * Hooked to term and term-relationship changes so the counts shown on the
  70. * manipulations tabs stay accurate.
  71. */
  72. public function bust_count_cache() {
  73. delete_transient('studiou_wcpcm_category_counts');
  74. delete_transient('studiou_wcpcm_media_cat_counts');
  75. }
  76. /**
  77. * Handle AJAX request to render a Category Manipulations tab partial.
  78. *
  79. * Each tab partial fetches only its own data, so the manipulations page
  80. * shell can render instantly and heavy calculations run on demand.
  81. */
  82. public function handle_load_tab_ajax() {
  83. // Clean any output buffers to prevent JSON corruption
  84. while (ob_get_level()) {
  85. ob_end_clean();
  86. }
  87. // Check nonce
  88. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  89. wp_send_json_error(array(
  90. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  91. ));
  92. return;
  93. }
  94. // Check permissions
  95. if (!current_user_can('manage_woocommerce')) {
  96. wp_send_json_error(array(
  97. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  98. ));
  99. return;
  100. }
  101. $tab = isset($_POST['tab']) ? sanitize_key($_POST['tab']) : '';
  102. $allowed = array('move', 'batch-description', 'delete-products', 'clear-media', 'remove-unassigned', 'upvp', 'notes');
  103. if (!in_array($tab, $allowed, true)) {
  104. wp_send_json_error(array(
  105. 'message' => __('Unknown tab', 'studiou-wc-product-cat-manage')
  106. ));
  107. return;
  108. }
  109. $partial = STUDIOU_WCPCM_PLUGIN_DIR . 'views/manipulations/tab-' . $tab . '.php';
  110. if (!file_exists($partial)) {
  111. wp_send_json_error(array(
  112. 'message' => __('Tab content not found', 'studiou-wc-product-cat-manage')
  113. ));
  114. return;
  115. }
  116. // Made available to the partial; each partial fetches only what it needs.
  117. $manipulator = $this;
  118. try {
  119. ob_start();
  120. include $partial;
  121. $html = ob_get_clean();
  122. wp_send_json_success(array(
  123. 'tab' => $tab,
  124. 'html' => $html
  125. ));
  126. } catch (Exception $e) {
  127. if (ob_get_level()) {
  128. ob_end_clean();
  129. }
  130. error_log('STUDIOU WC TABS: tab "' . $tab . '" render failed: ' . $e->getMessage());
  131. wp_send_json_error(array('message' => $e->getMessage()));
  132. }
  133. }
  134. /**
  135. * Handle AJAX batch description request
  136. */
  137. public function handle_batch_description_ajax() {
  138. // Clean all output buffers and prevent any output
  139. while (ob_get_level()) {
  140. ob_end_clean();
  141. }
  142. // Start a new output buffer to catch any unwanted output
  143. ob_start();
  144. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  145. $original_error_reporting = error_reporting();
  146. error_reporting(0);
  147. // Enable error logging only
  148. if (defined('WP_DEBUG') && WP_DEBUG) {
  149. error_log('STUDIOU WC: Batch description AJAX handler called');
  150. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  151. }
  152. try {
  153. // Check nonce
  154. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  155. wp_send_json_error(array(
  156. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  157. ));
  158. }
  159. // Check permissions
  160. if (!current_user_can('manage_woocommerce')) {
  161. wp_send_json_error(array(
  162. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  163. ));
  164. }
  165. // Validate input
  166. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  167. wp_send_json_error(array(
  168. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  169. ));
  170. }
  171. $selected_categories = array_map('intval', $_POST['selected_categories']);
  172. $description = sanitize_textarea_field($_POST['description']);
  173. // Debug logging
  174. if (defined('WP_DEBUG') && WP_DEBUG) {
  175. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  176. error_log('STUDIOU WC: Description: ' . $description);
  177. }
  178. // Validate categories
  179. if (empty($selected_categories)) {
  180. wp_send_json_error(array(
  181. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  182. ));
  183. }
  184. // Execute batch description operation
  185. $result = $this->update_categories_description($selected_categories, $description);
  186. // Debug logging
  187. if (defined('WP_DEBUG') && WP_DEBUG) {
  188. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  189. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  190. }
  191. // Clean any output that might have been generated
  192. ob_clean();
  193. // Return success response
  194. wp_send_json_success(array(
  195. 'message' => $result['message'],
  196. 'updated_count' => $result['updated_count'],
  197. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  198. ));
  199. } catch (Exception $e) {
  200. // Debug logging
  201. if (defined('WP_DEBUG') && WP_DEBUG) {
  202. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  203. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  204. }
  205. // Clean any output that might have been generated
  206. ob_clean();
  207. wp_send_json_error(array(
  208. 'message' => sprintf(
  209. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  210. $e->getMessage()
  211. )
  212. ));
  213. } finally {
  214. // Restore original error reporting
  215. error_reporting($original_error_reporting);
  216. // End the output buffer
  217. ob_end_clean();
  218. }
  219. }
  220. /**
  221. * Handle AJAX move products request
  222. */
  223. public function handle_move_products_ajax() {
  224. // Clean all output buffers and prevent any output
  225. while (ob_get_level()) {
  226. ob_end_clean();
  227. }
  228. // Start a new output buffer to catch any unwanted output
  229. ob_start();
  230. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  231. $original_error_reporting = error_reporting();
  232. error_reporting(0);
  233. // Enable error logging only
  234. if (defined('WP_DEBUG') && WP_DEBUG) {
  235. error_log('STUDIOU WC: AJAX handler called');
  236. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  237. }
  238. try {
  239. // Check nonce
  240. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  241. wp_send_json_error(array(
  242. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  243. ));
  244. }
  245. // Check permissions
  246. if (!current_user_can('manage_woocommerce')) {
  247. wp_send_json_error(array(
  248. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  249. ));
  250. }
  251. // Validate input
  252. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  253. wp_send_json_error(array(
  254. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  255. ));
  256. }
  257. $source_category_id = intval($_POST['source_category']);
  258. $target_category_id = intval($_POST['target_category']);
  259. // Debug logging
  260. if (defined('WP_DEBUG') && WP_DEBUG) {
  261. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  262. }
  263. // Validate categories
  264. if ($source_category_id === $target_category_id) {
  265. wp_send_json_error(array(
  266. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  267. ));
  268. }
  269. if ($source_category_id <= 0 || $target_category_id <= 0) {
  270. wp_send_json_error(array(
  271. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  272. ));
  273. }
  274. // Execute move operation
  275. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  276. // Debug logging
  277. if (defined('WP_DEBUG') && WP_DEBUG) {
  278. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  279. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  280. }
  281. // Clean any output that might have been generated
  282. ob_clean();
  283. // Return success response
  284. wp_send_json_success(array(
  285. 'message' => $result['message'],
  286. 'moved_count' => $result['moved_count'],
  287. 'source_count' => $result['source_count'],
  288. 'target_count' => $result['target_count'],
  289. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  290. ));
  291. } catch (Exception $e) {
  292. // Debug logging
  293. if (defined('WP_DEBUG') && WP_DEBUG) {
  294. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  295. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  296. }
  297. // Clean any output that might have been generated
  298. ob_clean();
  299. wp_send_json_error(array(
  300. 'message' => sprintf(
  301. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  302. $e->getMessage()
  303. )
  304. ));
  305. } finally {
  306. // Restore original error reporting
  307. error_reporting($original_error_reporting);
  308. // End the output buffer
  309. ob_end_clean();
  310. }
  311. }
  312. /**
  313. * v1.7.0 — M2: batched product move, step 1 (start).
  314. *
  315. * Returns the list of product IDs in the source category. JS chunks
  316. * them and calls handle_move_products_chunk_ajax in batches.
  317. */
  318. public function handle_move_products_start_ajax() {
  319. while (ob_get_level()) { ob_end_clean(); }
  320. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  321. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  322. }
  323. if (!current_user_can('manage_woocommerce')) {
  324. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  325. }
  326. $source = isset($_POST['source_category']) ? intval($_POST['source_category']) : 0;
  327. $target = isset($_POST['target_category']) ? intval($_POST['target_category']) : 0;
  328. if ($source <= 0 || $target <= 0) {
  329. wp_send_json_error(array('message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')));
  330. }
  331. if ($source === $target) {
  332. wp_send_json_error(array('message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')));
  333. }
  334. $source_term = get_term($source, 'product_cat');
  335. $target_term = get_term($target, 'product_cat');
  336. if (is_wp_error($source_term) || !$source_term || is_wp_error($target_term) || !$target_term) {
  337. wp_send_json_error(array('message' => __('Invalid category specified', 'studiou-wc-product-cat-manage')));
  338. }
  339. $product_ids = $this->get_products_in_category($source);
  340. wp_send_json_success(array(
  341. 'product_ids' => array_values(array_map('intval', $product_ids)),
  342. 'total' => count($product_ids),
  343. 'source_name' => $source_term->name,
  344. 'target_name' => $target_term->name,
  345. ));
  346. }
  347. /**
  348. * v1.7.0 — M2: batched product move, step 2 (chunk).
  349. *
  350. * Moves the supplied product IDs from source to target category.
  351. * wp_set_post_terms is idempotent, so a re-run of an already-moved
  352. * chunk (e.g. after a network retry) is safe.
  353. */
  354. public function handle_move_products_chunk_ajax() {
  355. while (ob_get_level()) { ob_end_clean(); }
  356. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  357. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  358. }
  359. if (!current_user_can('manage_woocommerce')) {
  360. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  361. }
  362. $source = isset($_POST['source_category']) ? intval($_POST['source_category']) : 0;
  363. $target = isset($_POST['target_category']) ? intval($_POST['target_category']) : 0;
  364. $ids = isset($_POST['product_ids']) && is_array($_POST['product_ids'])
  365. ? array_values(array_map('intval', $_POST['product_ids']))
  366. : array();
  367. if ($source <= 0 || $target <= 0 || $source === $target || empty($ids)) {
  368. wp_send_json_error(array('message' => __('Invalid request', 'studiou-wc-product-cat-manage')));
  369. }
  370. $moved = 0;
  371. $failed = 0;
  372. foreach ($ids as $pid) {
  373. $current = wp_get_post_terms($pid, 'product_cat', array('fields' => 'ids'));
  374. if (is_wp_error($current)) {
  375. $failed++;
  376. continue;
  377. }
  378. $new = array_diff($current, array($source));
  379. $new[] = $target;
  380. $new = array_values(array_unique($new));
  381. $r = wp_set_post_terms($pid, $new, 'product_cat');
  382. if (is_wp_error($r)) {
  383. $failed++;
  384. } else {
  385. $moved++;
  386. }
  387. }
  388. wp_send_json_success(array(
  389. 'moved' => $moved,
  390. 'failed' => $failed,
  391. ));
  392. }
  393. /**
  394. * Move all products from source category to target category
  395. *
  396. * @param int $source_category_id Source category ID
  397. * @param int $target_category_id Target category ID
  398. * @return array Result with counts and message
  399. * @throws Exception On error
  400. */
  401. public function move_products_between_categories($source_category_id, $target_category_id) {
  402. // Get source and target category terms
  403. $source_category = get_term($source_category_id, 'product_cat');
  404. $target_category = get_term($target_category_id, 'product_cat');
  405. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  406. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  407. }
  408. // Get initial count of products in source category using direct DB query
  409. $initial_source_count = $this->get_category_product_count($source_category_id);
  410. // Check if source category has any products
  411. if ($initial_source_count === 0) {
  412. $message = sprintf(
  413. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  414. $source_category->name
  415. );
  416. return array(
  417. 'moved_count' => 0,
  418. 'source_count' => 0,
  419. 'target_count' => $this->get_category_product_count($target_category_id),
  420. 'message' => $message
  421. );
  422. }
  423. // Get all products in source category using direct DB query
  424. $products = $this->get_products_in_category($source_category_id);
  425. $moved_count = 0;
  426. $failed_count = 0;
  427. if (defined('WP_DEBUG') && WP_DEBUG) {
  428. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  429. }
  430. // Move each product
  431. foreach ($products as $product_id) {
  432. // Get current categories for the product
  433. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  434. if (is_wp_error($current_categories)) {
  435. $failed_count++;
  436. if (defined('WP_DEBUG') && WP_DEBUG) {
  437. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  438. }
  439. continue;
  440. }
  441. // Remove source category and add target category
  442. $new_categories = array_diff($current_categories, array($source_category_id));
  443. $new_categories[] = $target_category_id;
  444. // Update product categories
  445. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  446. if (!is_wp_error($result)) {
  447. $moved_count++;
  448. if (defined('WP_DEBUG') && WP_DEBUG) {
  449. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  450. }
  451. } else {
  452. $failed_count++;
  453. if (defined('WP_DEBUG') && WP_DEBUG) {
  454. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  455. }
  456. }
  457. }
  458. // Get updated counts using direct DB query
  459. $source_count = $this->get_category_product_count($source_category_id);
  460. $target_count = $this->get_category_product_count($target_category_id);
  461. // Generate detailed result message
  462. if ($moved_count === 0 && count($products) > 0) {
  463. $message = sprintf(
  464. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  465. $source_category->name,
  466. $target_category->name,
  467. count($products)
  468. );
  469. } else {
  470. $message = sprintf(
  471. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  472. $moved_count,
  473. $source_category->name,
  474. $target_category->name,
  475. $source_count,
  476. $target_count
  477. );
  478. if ($failed_count > 0) {
  479. $message .= ' ' . sprintf(
  480. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  481. $failed_count
  482. );
  483. }
  484. }
  485. return array(
  486. 'moved_count' => $moved_count,
  487. 'source_count' => $source_count,
  488. 'target_count' => $target_count,
  489. 'failed_count' => $failed_count,
  490. 'message' => $message
  491. );
  492. }
  493. /**
  494. * Get product count for a category
  495. *
  496. * @param int $category_id Category ID
  497. * @return int Product count
  498. */
  499. private function get_category_product_count($category_id) {
  500. global $wpdb;
  501. // Use direct database query for more accurate counting
  502. $sql = "
  503. SELECT COUNT(DISTINCT p.ID)
  504. FROM {$wpdb->posts} p
  505. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  506. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  507. WHERE tt.term_id = %d
  508. AND tt.taxonomy = 'product_cat'
  509. AND p.post_type = 'product'
  510. AND p.post_status IN ('publish', 'private', 'draft')
  511. ";
  512. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  513. if (defined('WP_DEBUG') && WP_DEBUG) {
  514. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  515. }
  516. return intval($count);
  517. }
  518. /**
  519. * Get all products in a category
  520. *
  521. * @param int $category_id Category ID
  522. * @return array Array of product IDs
  523. */
  524. private function get_products_in_category($category_id) {
  525. global $wpdb;
  526. // Use direct database query to get products
  527. $sql = "
  528. SELECT DISTINCT p.ID
  529. FROM {$wpdb->posts} p
  530. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  531. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  532. WHERE tt.term_id = %d
  533. AND tt.taxonomy = 'product_cat'
  534. AND p.post_type = 'product'
  535. AND p.post_status IN ('publish', 'private', 'draft')
  536. ";
  537. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  538. if (defined('WP_DEBUG') && WP_DEBUG) {
  539. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  540. if (!empty($products)) {
  541. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  542. }
  543. }
  544. return $products ? array_map('intval', $products) : array();
  545. }
  546. /**
  547. * Update descriptions for multiple categories
  548. *
  549. * @param array $category_ids Array of category IDs
  550. * @param string $description New description for categories
  551. * @return array Result with counts and message
  552. * @throws Exception On error
  553. */
  554. public function update_categories_description($category_ids, $description) {
  555. $updated_count = 0;
  556. $failed_count = 0;
  557. $category_names = array();
  558. // Debug logging
  559. if (defined('WP_DEBUG') && WP_DEBUG) {
  560. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  561. }
  562. // Update each category
  563. foreach ($category_ids as $category_id) {
  564. // Get category term
  565. $category = get_term($category_id, 'product_cat');
  566. if (is_wp_error($category) || !$category) {
  567. $failed_count++;
  568. if (defined('WP_DEBUG') && WP_DEBUG) {
  569. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  570. }
  571. continue;
  572. }
  573. // Update category description
  574. $result = wp_update_term($category_id, 'product_cat', array(
  575. 'description' => $description
  576. ));
  577. if (!is_wp_error($result)) {
  578. $updated_count++;
  579. $category_names[] = $category->name;
  580. if (defined('WP_DEBUG') && WP_DEBUG) {
  581. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  582. }
  583. } else {
  584. $failed_count++;
  585. if (defined('WP_DEBUG') && WP_DEBUG) {
  586. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  587. }
  588. }
  589. }
  590. // Generate result message
  591. if ($updated_count === 0) {
  592. $message = sprintf(
  593. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  594. $failed_count
  595. );
  596. } else {
  597. $message = sprintf(
  598. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  599. $updated_count,
  600. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  601. );
  602. if ($failed_count > 0) {
  603. $message .= ' ' . sprintf(
  604. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  605. $failed_count
  606. );
  607. }
  608. }
  609. return array(
  610. 'updated_count' => $updated_count,
  611. 'failed_count' => $failed_count,
  612. 'message' => $message
  613. );
  614. }
  615. /**
  616. * Get all categories with product counts for select lists.
  617. *
  618. * Transient-cached wrapper around get_categories_with_counts_uncached().
  619. * The N+1 per-category count queries are expensive on large stores, so the
  620. * result is cached for 5 minutes and busted on any category change.
  621. *
  622. * @return array Array of categories with ID, name, and product count
  623. */
  624. public function get_categories_with_counts() {
  625. $data = get_transient('studiou_wcpcm_category_counts');
  626. if (false === $data) {
  627. $data = $this->get_categories_with_counts_uncached();
  628. set_transient('studiou_wcpcm_category_counts', $data, 5 * MINUTE_IN_SECONDS);
  629. }
  630. return $data;
  631. }
  632. /**
  633. * Get all categories with product counts for select lists (uncached).
  634. *
  635. * Queries the product_cat terms directly via $wpdb instead of get_terms()
  636. * on purpose: the WooCommerce Protected Categories plugin filters
  637. * get_terms() and hides protected categories in admin-ajax / front-end
  638. * contexts. Since v1.6.0 the manipulations tabs fetch this list inside an
  639. * admin-ajax request, so get_terms() would drop protected categories from
  640. * the dropdowns. Admins must be able to see and operate on every category,
  641. * protected ones included, so we bypass the term-query filters entirely.
  642. *
  643. * @return array Array of categories with ID, name, and product count
  644. */
  645. public function get_categories_with_counts_uncached() {
  646. global $wpdb;
  647. // v1.7.1 — M9: replace the per-category get_category_product_count()
  648. // loop (N+1) with a single aggregate query. The naive
  649. // term_relationships count would over-count trashed/pending/
  650. // auto-draft products because trashing a product does NOT remove
  651. // its term relationship — a category emptied via "Delete products
  652. // in category" could still display a non-zero count. So we JOIN
  653. // wp_posts and apply the SAME filters get_category_product_count()
  654. // uses (post_type='product', post_status IN publish/private/draft),
  655. // with the filters in the ON clause so zero-count categories
  656. // survive the LEFT JOIN.
  657. $sql = $wpdb->prepare("
  658. SELECT t.term_id, t.name, COUNT(DISTINCT p.ID) AS cnt
  659. FROM {$wpdb->terms} t
  660. INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
  661. LEFT JOIN {$wpdb->term_relationships} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
  662. LEFT JOIN {$wpdb->posts} p
  663. ON p.ID = tr.object_id
  664. AND p.post_type = %s
  665. AND p.post_status IN ('publish','private','draft')
  666. WHERE tt.taxonomy = %s
  667. GROUP BY t.term_id, t.name
  668. ORDER BY t.name ASC
  669. ", 'product', 'product_cat');
  670. $rows = $wpdb->get_results($sql);
  671. $categories_with_counts = array();
  672. if (!empty($rows)) {
  673. foreach ($rows as $row) {
  674. $count = (int) $row->cnt;
  675. $categories_with_counts[] = array(
  676. 'id' => (int) $row->term_id,
  677. 'name' => $row->name,
  678. 'count' => $count,
  679. 'display_name' => sprintf('%s (%d products)', $row->name, $count),
  680. );
  681. }
  682. }
  683. return $categories_with_counts;
  684. }
  685. /**
  686. * Handle AJAX delete products request (initial request to get product IDs)
  687. */
  688. public function handle_delete_products_ajax() {
  689. // Clean all output buffers and prevent any output
  690. while (ob_get_level()) {
  691. ob_end_clean();
  692. }
  693. // Start a new output buffer to catch any unwanted output
  694. ob_start();
  695. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  696. $original_error_reporting = error_reporting();
  697. error_reporting(0);
  698. // Enable error logging only
  699. if (defined('WP_DEBUG') && WP_DEBUG) {
  700. error_log('STUDIOU WC: Delete products AJAX handler called');
  701. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  702. }
  703. try {
  704. // Check nonce
  705. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  706. wp_send_json_error(array(
  707. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  708. ));
  709. }
  710. // Check permissions
  711. if (!current_user_can('manage_woocommerce')) {
  712. wp_send_json_error(array(
  713. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  714. ));
  715. }
  716. // Validate input
  717. if (!isset($_POST['delete_categories'])) {
  718. wp_send_json_error(array(
  719. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  720. ));
  721. }
  722. $category_ids = array_map('intval', $_POST['delete_categories']);
  723. // Debug logging
  724. if (defined('WP_DEBUG') && WP_DEBUG) {
  725. error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
  726. }
  727. // Validate categories
  728. if (empty($category_ids)) {
  729. wp_send_json_error(array(
  730. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  731. ));
  732. }
  733. // Get all products from selected categories
  734. $product_ids = $this->get_products_from_categories($category_ids);
  735. // Debug logging
  736. if (defined('WP_DEBUG') && WP_DEBUG) {
  737. error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
  738. }
  739. // Clean any output that might have been generated
  740. ob_clean();
  741. // Return product IDs for batch processing
  742. wp_send_json_success(array(
  743. 'product_ids' => $product_ids,
  744. 'total_count' => count($product_ids),
  745. 'message' => sprintf(
  746. __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
  747. count($product_ids)
  748. )
  749. ));
  750. } catch (Exception $e) {
  751. // Debug logging
  752. if (defined('WP_DEBUG') && WP_DEBUG) {
  753. error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
  754. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  755. }
  756. // Clean any output that might have been generated
  757. ob_clean();
  758. wp_send_json_error(array(
  759. 'message' => sprintf(
  760. __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
  761. $e->getMessage()
  762. )
  763. ));
  764. } finally {
  765. // Restore original error reporting
  766. error_reporting($original_error_reporting);
  767. // End the output buffer
  768. ob_end_clean();
  769. }
  770. }
  771. /**
  772. * Handle AJAX delete products batch request (processes products in batches)
  773. */
  774. public function handle_delete_products_batch_ajax() {
  775. // Clean all output buffers and prevent any output
  776. while (ob_get_level()) {
  777. ob_end_clean();
  778. }
  779. // Start a new output buffer to catch any unwanted output
  780. ob_start();
  781. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  782. $original_error_reporting = error_reporting();
  783. error_reporting(0);
  784. // Enable error logging only
  785. if (defined('WP_DEBUG') && WP_DEBUG) {
  786. error_log('STUDIOU WC: Delete products batch AJAX handler called');
  787. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  788. }
  789. try {
  790. // Check nonce
  791. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  792. wp_send_json_error(array(
  793. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  794. ));
  795. }
  796. // Check permissions
  797. if (!current_user_can('manage_woocommerce')) {
  798. wp_send_json_error(array(
  799. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  800. ));
  801. }
  802. // Validate input
  803. if (!isset($_POST['product_ids'])) {
  804. wp_send_json_error(array(
  805. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  806. ));
  807. }
  808. $product_ids = array_map('intval', $_POST['product_ids']);
  809. // Debug logging
  810. if (defined('WP_DEBUG') && WP_DEBUG) {
  811. error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
  812. }
  813. // Delete products in this batch
  814. $result = $this->delete_products_batch($product_ids);
  815. // Debug logging
  816. if (defined('WP_DEBUG') && WP_DEBUG) {
  817. error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  818. }
  819. // Clean any output that might have been generated
  820. ob_clean();
  821. // Return success response
  822. wp_send_json_success(array(
  823. 'deleted_count' => $result['deleted_count'],
  824. 'failed_count' => $result['failed_count'],
  825. 'failed_products' => $result['failed_products']
  826. ));
  827. } catch (Exception $e) {
  828. // Debug logging
  829. if (defined('WP_DEBUG') && WP_DEBUG) {
  830. error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
  831. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  832. }
  833. // Clean any output that might have been generated
  834. ob_clean();
  835. wp_send_json_error(array(
  836. 'message' => sprintf(
  837. __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
  838. $e->getMessage()
  839. )
  840. ));
  841. } finally {
  842. // Restore original error reporting
  843. error_reporting($original_error_reporting);
  844. // End the output buffer
  845. ob_end_clean();
  846. }
  847. }
  848. /**
  849. * Get all products from multiple categories
  850. *
  851. * @param array $category_ids Array of category IDs
  852. * @return array Array of unique product IDs (including parent products with variants)
  853. */
  854. private function get_products_from_categories($category_ids) {
  855. global $wpdb;
  856. if (empty($category_ids)) {
  857. return array();
  858. }
  859. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  860. // Get all products from selected categories (both simple and parent products)
  861. $sql = "
  862. SELECT DISTINCT p.ID
  863. FROM {$wpdb->posts} p
  864. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  865. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  866. WHERE tt.term_id IN ($placeholders)
  867. AND tt.taxonomy = 'product_cat'
  868. AND p.post_type = 'product'
  869. AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
  870. ";
  871. $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
  872. if (defined('WP_DEBUG') && WP_DEBUG) {
  873. error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
  874. }
  875. return $products ? array_map('intval', $products) : array();
  876. }
  877. /**
  878. * Delete a batch of products and their variants
  879. *
  880. * @param array $product_ids Array of product IDs to delete
  881. * @return array Result with counts
  882. */
  883. private function delete_products_batch($product_ids) {
  884. $deleted_count = 0;
  885. $failed_count = 0;
  886. $failed_products = array();
  887. foreach ($product_ids as $product_id) {
  888. try {
  889. // Get the product object
  890. $product = wc_get_product($product_id);
  891. if (!$product) {
  892. $failed_count++;
  893. $failed_products[] = $product_id;
  894. if (defined('WP_DEBUG') && WP_DEBUG) {
  895. error_log('STUDIOU WC: Product ' . $product_id . ' not found');
  896. }
  897. continue;
  898. }
  899. // If it's a variable product, delete all variations first
  900. if ($product->is_type('variable')) {
  901. $variations = $product->get_children();
  902. if (defined('WP_DEBUG') && WP_DEBUG) {
  903. error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
  904. }
  905. foreach ($variations as $variation_id) {
  906. $variation = wc_get_product($variation_id);
  907. if ($variation) {
  908. $variation->delete(true); // true = force delete permanently
  909. }
  910. }
  911. }
  912. // Delete the product permanently
  913. $result = $product->delete(true); // true = force delete permanently
  914. if ($result) {
  915. $deleted_count++;
  916. if (defined('WP_DEBUG') && WP_DEBUG) {
  917. error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
  918. }
  919. } else {
  920. $failed_count++;
  921. $failed_products[] = $product_id;
  922. if (defined('WP_DEBUG') && WP_DEBUG) {
  923. error_log('STUDIOU WC: Failed to delete product ' . $product_id);
  924. }
  925. }
  926. } catch (Exception $e) {
  927. $failed_count++;
  928. $failed_products[] = $product_id;
  929. if (defined('WP_DEBUG') && WP_DEBUG) {
  930. error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
  931. }
  932. }
  933. }
  934. return array(
  935. 'deleted_count' => $deleted_count,
  936. 'failed_count' => $failed_count,
  937. 'failed_products' => $failed_products
  938. );
  939. }
  940. /**
  941. * Get all media categories with file counts for select lists.
  942. *
  943. * Transient-cached wrapper around get_media_categories_with_counts_uncached().
  944. *
  945. * @return array Array of media categories with ID, name, and file count
  946. */
  947. public function get_media_categories_with_counts() {
  948. $data = get_transient('studiou_wcpcm_media_cat_counts');
  949. if (false === $data) {
  950. $data = $this->get_media_categories_with_counts_uncached();
  951. set_transient('studiou_wcpcm_media_cat_counts', $data, 5 * MINUTE_IN_SECONDS);
  952. }
  953. return $data;
  954. }
  955. /**
  956. * Get all media categories with file counts for select lists (uncached).
  957. *
  958. * @return array Array of media categories with ID, name, and file count
  959. */
  960. public function get_media_categories_with_counts_uncached() {
  961. $taxonomy = $this->get_media_category_taxonomy();
  962. if (!$taxonomy) {
  963. return array();
  964. }
  965. $args = array(
  966. 'taxonomy' => $taxonomy,
  967. 'orderby' => 'name',
  968. 'hide_empty' => false,
  969. );
  970. $categories = get_terms($args);
  971. $categories_with_counts = array();
  972. if (!is_wp_error($categories)) {
  973. foreach ($categories as $category) {
  974. $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
  975. $categories_with_counts[] = array(
  976. 'id' => $category->term_id,
  977. 'name' => $category->name,
  978. 'count' => $file_count,
  979. 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
  980. );
  981. }
  982. }
  983. return $categories_with_counts;
  984. }
  985. /**
  986. * Get the media category taxonomy name
  987. *
  988. * Checks for common media category taxonomies used by popular plugins
  989. *
  990. * @return string|false Taxonomy name or false if none found
  991. */
  992. private function get_media_category_taxonomy() {
  993. $possible_taxonomies = array(
  994. 'media_category',
  995. 'attachment_category',
  996. 'media-category',
  997. );
  998. foreach ($possible_taxonomies as $taxonomy) {
  999. if (taxonomy_exists($taxonomy)) {
  1000. error_log('STUDIOU WC MEDIA: Detected media taxonomy: ' . $taxonomy);
  1001. return $taxonomy;
  1002. }
  1003. }
  1004. // Try to find any taxonomy registered for attachments
  1005. $attachment_taxonomies = get_object_taxonomies('attachment', 'names');
  1006. if (!empty($attachment_taxonomies)) {
  1007. // Filter out built-in taxonomies
  1008. $custom_taxonomies = array_filter($attachment_taxonomies, function($tax) {
  1009. return !in_array($tax, array('post_tag', 'category', 'post_format'));
  1010. });
  1011. if (!empty($custom_taxonomies)) {
  1012. $found = reset($custom_taxonomies);
  1013. error_log('STUDIOU WC MEDIA: Auto-detected attachment taxonomy: ' . $found);
  1014. return $found;
  1015. }
  1016. }
  1017. error_log('STUDIOU WC MEDIA: No media category taxonomy found. Registered attachment taxonomies: ' . implode(', ', $attachment_taxonomies ?? array()));
  1018. return false;
  1019. }
  1020. /**
  1021. * Get file count for a media category
  1022. *
  1023. * @param int $category_id Category term ID
  1024. * @param string $taxonomy Taxonomy name
  1025. * @return int File count
  1026. */
  1027. private function get_media_category_file_count($category_id, $taxonomy) {
  1028. global $wpdb;
  1029. $sql = "
  1030. SELECT COUNT(DISTINCT p.ID)
  1031. FROM {$wpdb->posts} p
  1032. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1033. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1034. WHERE tt.term_id = %d
  1035. AND tt.taxonomy = %s
  1036. AND p.post_type = 'attachment'
  1037. ";
  1038. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
  1039. return intval($count);
  1040. }
  1041. /**
  1042. * Get all media IDs from multiple media categories
  1043. *
  1044. * @param array $category_ids Array of category term IDs
  1045. * @return array Array of unique attachment IDs
  1046. */
  1047. private function get_media_from_categories($category_ids) {
  1048. global $wpdb;
  1049. $taxonomy = $this->get_media_category_taxonomy();
  1050. error_log('STUDIOU WC MEDIA: get_media_from_categories called - taxonomy: ' . ($taxonomy ?: 'false') . ', category_ids: ' . implode(', ', $category_ids));
  1051. if (!$taxonomy || empty($category_ids)) {
  1052. error_log('STUDIOU WC MEDIA: No taxonomy or empty category_ids, returning empty');
  1053. return array();
  1054. }
  1055. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  1056. $sql = "
  1057. SELECT DISTINCT p.ID
  1058. FROM {$wpdb->posts} p
  1059. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1060. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1061. WHERE tt.term_id IN ($placeholders)
  1062. AND tt.taxonomy = %s
  1063. AND p.post_type = 'attachment'
  1064. ";
  1065. $params = array_merge($category_ids, array($taxonomy));
  1066. $media = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1067. error_log('STUDIOU WC MEDIA: Query found ' . ($media ? count($media) : 0) . ' media files');
  1068. return $media ? array_map('intval', $media) : array();
  1069. }
  1070. /**
  1071. * Delete a batch of media files permanently
  1072. *
  1073. * @param array $media_ids Array of attachment IDs to delete
  1074. * @return array Result with counts
  1075. */
  1076. private function delete_media_batch($media_ids) {
  1077. global $wpdb;
  1078. $deleted_count = 0;
  1079. $failed_count = 0;
  1080. $failed_media = array();
  1081. $affected_term_ids = array();
  1082. $taxonomy = $this->get_media_category_taxonomy();
  1083. // Ensure required file functions are loaded
  1084. if (!function_exists('wp_delete_attachment')) {
  1085. require_once ABSPATH . 'wp-admin/includes/post.php';
  1086. }
  1087. if (!function_exists('wp_delete_file')) {
  1088. require_once ABSPATH . 'wp-includes/functions.php';
  1089. }
  1090. error_log('STUDIOU WC MEDIA: delete_media_batch called with ' . count($media_ids) . ' media IDs');
  1091. foreach ($media_ids as $media_id) {
  1092. try {
  1093. $attachment = get_post($media_id);
  1094. if (!$attachment || $attachment->post_type !== 'attachment') {
  1095. $failed_count++;
  1096. $failed_media[] = $media_id;
  1097. error_log('STUDIOU WC MEDIA: Media file ' . $media_id . ' not found or not an attachment');
  1098. continue;
  1099. }
  1100. // Collect affected term IDs before deletion for count update
  1101. if ($taxonomy) {
  1102. $terms = wp_get_object_terms($media_id, $taxonomy, array('fields' => 'ids'));
  1103. if (!is_wp_error($terms)) {
  1104. $affected_term_ids = array_merge($affected_term_ids, $terms);
  1105. }
  1106. }
  1107. // Get file paths BEFORE deletion
  1108. $file = get_attached_file($media_id);
  1109. $meta = wp_get_attachment_metadata($media_id);
  1110. $upload_dir = wp_get_upload_dir();
  1111. error_log('STUDIOU WC MEDIA: Deleting media ID ' . $media_id . ', file: ' . ($file ?: 'none'));
  1112. // Attempt standard WordPress deletion
  1113. wp_delete_attachment($media_id, true);
  1114. // Verify the post was actually deleted
  1115. $still_exists = $wpdb->get_var($wpdb->prepare(
  1116. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  1117. $media_id
  1118. ));
  1119. if ($still_exists) {
  1120. error_log('STUDIOU WC MEDIA: wp_delete_attachment did not delete post ' . $media_id . ', forcing manual deletion');
  1121. // Force manual deletion: remove term relationships
  1122. $all_taxonomies = get_object_taxonomies('attachment');
  1123. if (!empty($all_taxonomies)) {
  1124. wp_delete_object_term_relationships($media_id, $all_taxonomies);
  1125. }
  1126. // Remove all post meta
  1127. $wpdb->delete($wpdb->postmeta, array('post_id' => $media_id));
  1128. // Remove the post itself
  1129. $wpdb->delete($wpdb->posts, array('ID' => $media_id));
  1130. // Clean cache
  1131. clean_post_cache($media_id);
  1132. }
  1133. // Delete physical files from disk
  1134. if ($file && file_exists($file)) {
  1135. @unlink($file);
  1136. error_log('STUDIOU WC MEDIA: Deleted main file: ' . $file);
  1137. }
  1138. // Delete thumbnail/intermediate sizes
  1139. if (!empty($meta['sizes']) && !empty($upload_dir['basedir'])) {
  1140. $file_dir = !empty($file) ? trailingslashit(dirname($file)) : '';
  1141. foreach ($meta['sizes'] as $size => $sizeinfo) {
  1142. if (!empty($sizeinfo['file'])) {
  1143. $intermediate_file = $file_dir . $sizeinfo['file'];
  1144. if (file_exists($intermediate_file)) {
  1145. @unlink($intermediate_file);
  1146. }
  1147. }
  1148. }
  1149. }
  1150. // Final verification
  1151. $final_check = $wpdb->get_var($wpdb->prepare(
  1152. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  1153. $media_id
  1154. ));
  1155. if (!$final_check) {
  1156. $deleted_count++;
  1157. error_log('STUDIOU WC MEDIA: Successfully deleted media file ' . $media_id);
  1158. } else {
  1159. $failed_count++;
  1160. $failed_media[] = $media_id;
  1161. error_log('STUDIOU WC MEDIA: FAILED to delete media file ' . $media_id . ' even after manual cleanup');
  1162. }
  1163. } catch (Exception $e) {
  1164. $failed_count++;
  1165. $failed_media[] = $media_id;
  1166. error_log('STUDIOU WC MEDIA: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
  1167. }
  1168. }
  1169. // Force update term counts for affected categories
  1170. if ($taxonomy && !empty($affected_term_ids)) {
  1171. $affected_term_ids = array_unique($affected_term_ids);
  1172. wp_update_term_count_now($affected_term_ids, $taxonomy);
  1173. error_log('STUDIOU WC MEDIA: Updated term counts for term IDs: ' . implode(', ', $affected_term_ids));
  1174. }
  1175. error_log('STUDIOU WC MEDIA: Batch result - deleted: ' . $deleted_count . ', failed: ' . $failed_count);
  1176. return array(
  1177. 'deleted_count' => $deleted_count,
  1178. 'failed_count' => $failed_count,
  1179. 'failed_media' => $failed_media
  1180. );
  1181. }
  1182. /**
  1183. * Handle AJAX clear media request (initial request to get media IDs)
  1184. */
  1185. public function handle_clear_media_ajax() {
  1186. while (ob_get_level()) {
  1187. ob_end_clean();
  1188. }
  1189. ob_start();
  1190. $original_error_reporting = error_reporting();
  1191. error_reporting(0);
  1192. error_log('STUDIOU WC MEDIA: Clear media AJAX handler called');
  1193. error_log('STUDIOU WC MEDIA: POST data: ' . print_r($_POST, true));
  1194. try {
  1195. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1196. error_log('STUDIOU WC MEDIA: Nonce verification failed');
  1197. wp_send_json_error(array(
  1198. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  1199. ));
  1200. return;
  1201. }
  1202. if (!current_user_can('manage_woocommerce')) {
  1203. error_log('STUDIOU WC MEDIA: Permission check failed');
  1204. wp_send_json_error(array(
  1205. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  1206. ));
  1207. return;
  1208. }
  1209. if (!isset($_POST['media_categories'])) {
  1210. error_log('STUDIOU WC MEDIA: media_categories not in POST data');
  1211. wp_send_json_error(array(
  1212. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  1213. ));
  1214. return;
  1215. }
  1216. $category_ids = array_map('intval', $_POST['media_categories']);
  1217. if (empty($category_ids)) {
  1218. error_log('STUDIOU WC MEDIA: Empty category_ids after intval mapping');
  1219. wp_send_json_error(array(
  1220. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  1221. ));
  1222. return;
  1223. }
  1224. $media_ids = $this->get_media_from_categories($category_ids);
  1225. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' media files to delete from categories: ' . implode(', ', $category_ids));
  1226. ob_clean();
  1227. wp_send_json_success(array(
  1228. 'media_ids' => $media_ids,
  1229. 'total_count' => count($media_ids),
  1230. 'message' => sprintf(
  1231. __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
  1232. count($media_ids)
  1233. )
  1234. ));
  1235. } catch (Exception $e) {
  1236. error_log('STUDIOU WC MEDIA: Clear media operation failed - ' . $e->getMessage());
  1237. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1238. ob_clean();
  1239. wp_send_json_error(array(
  1240. 'message' => sprintf(
  1241. __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
  1242. $e->getMessage()
  1243. )
  1244. ));
  1245. } finally {
  1246. error_reporting($original_error_reporting);
  1247. ob_end_clean();
  1248. }
  1249. }
  1250. /**
  1251. * Handle AJAX clear media batch request (processes media in batches)
  1252. */
  1253. public function handle_clear_media_batch_ajax() {
  1254. while (ob_get_level()) {
  1255. ob_end_clean();
  1256. }
  1257. ob_start();
  1258. $original_error_reporting = error_reporting();
  1259. error_reporting(0);
  1260. error_log('STUDIOU WC MEDIA: Clear media batch AJAX handler called');
  1261. try {
  1262. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1263. error_log('STUDIOU WC MEDIA: Batch nonce verification failed');
  1264. wp_send_json_error(array(
  1265. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  1266. ));
  1267. return;
  1268. }
  1269. if (!current_user_can('manage_woocommerce')) {
  1270. error_log('STUDIOU WC MEDIA: Batch permission check failed');
  1271. wp_send_json_error(array(
  1272. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  1273. ));
  1274. return;
  1275. }
  1276. if (!isset($_POST['media_ids'])) {
  1277. error_log('STUDIOU WC MEDIA: media_ids not in POST data');
  1278. wp_send_json_error(array(
  1279. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  1280. ));
  1281. return;
  1282. }
  1283. $media_ids = array_map('intval', $_POST['media_ids']);
  1284. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' media files for deletion');
  1285. $result = $this->delete_media_batch($media_ids);
  1286. error_log('STUDIOU WC MEDIA: Batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1287. ob_clean();
  1288. wp_send_json_success(array(
  1289. 'deleted_count' => $result['deleted_count'],
  1290. 'failed_count' => $result['failed_count'],
  1291. 'failed_media' => $result['failed_media']
  1292. ));
  1293. } catch (Exception $e) {
  1294. error_log('STUDIOU WC MEDIA: Clear media batch operation failed - ' . $e->getMessage());
  1295. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1296. ob_clean();
  1297. wp_send_json_error(array(
  1298. 'message' => sprintf(
  1299. __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
  1300. $e->getMessage()
  1301. )
  1302. ));
  1303. } finally {
  1304. error_reporting($original_error_reporting);
  1305. ob_end_clean();
  1306. }
  1307. }
  1308. /**
  1309. * Get count of unassigned unused media files
  1310. *
  1311. * @return int Count of media files not in any category and not referenced
  1312. */
  1313. public function get_unassigned_unused_media_count() {
  1314. $ids = $this->get_unassigned_unused_media_ids();
  1315. return count($ids);
  1316. }
  1317. /**
  1318. * Get IDs of media files that are not assigned to any media category
  1319. * and not used as featured image, product gallery image, or attached to any post.
  1320. *
  1321. * @return array Array of attachment IDs
  1322. */
  1323. public function get_unassigned_unused_media_ids() {
  1324. global $wpdb;
  1325. $taxonomy = $this->get_media_category_taxonomy();
  1326. // Base query: all attachments not used as featured image and not attached to a post
  1327. $sql = "
  1328. SELECT a.ID
  1329. FROM {$wpdb->posts} a
  1330. LEFT JOIN {$wpdb->postmeta} pm_thumb
  1331. ON a.ID = CAST(pm_thumb.meta_value AS UNSIGNED)
  1332. AND pm_thumb.meta_key = '_thumbnail_id'
  1333. WHERE a.post_type = 'attachment'
  1334. AND a.post_parent = 0
  1335. AND pm_thumb.meta_id IS NULL
  1336. ";
  1337. // If media category taxonomy exists, also exclude categorized media
  1338. if ($taxonomy) {
  1339. $sql .= $wpdb->prepare("
  1340. AND a.ID NOT IN (
  1341. SELECT tr.object_id
  1342. FROM {$wpdb->term_relationships} tr
  1343. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1344. WHERE tt.taxonomy = %s
  1345. )
  1346. ", $taxonomy);
  1347. }
  1348. $media_ids = $wpdb->get_col($sql);
  1349. if (empty($media_ids)) {
  1350. return array();
  1351. }
  1352. $media_ids = array_map('intval', $media_ids);
  1353. // Filter out media used in WooCommerce product galleries (_product_image_gallery)
  1354. $gallery_meta = $wpdb->get_col(
  1355. "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value != ''"
  1356. );
  1357. if (!empty($gallery_meta)) {
  1358. $gallery_ids = array();
  1359. foreach ($gallery_meta as $gallery_value) {
  1360. $ids = array_map('intval', array_filter(explode(',', $gallery_value)));
  1361. $gallery_ids = array_merge($gallery_ids, $ids);
  1362. }
  1363. $gallery_ids = array_unique($gallery_ids);
  1364. if (!empty($gallery_ids)) {
  1365. $media_ids = array_diff($media_ids, $gallery_ids);
  1366. }
  1367. }
  1368. // v1.6.2 — narrow blast radius. The base query above does not see
  1369. // attachments referenced from term meta (WooCommerce product-category
  1370. // images are stored as termmeta 'thumbnail_id'), nor customizer images
  1371. // (custom logo, site icon, header image). Without these exclusions,
  1372. // running "Remove Not Assigned Media" silently destroys category
  1373. // artwork. NOTE: content-embedded, ACF/meta-field, and downloadable-
  1374. // product images are still NOT detected — see the warning in
  1375. // tab-remove-unassigned.php. The preview-list inversion (plan-02) is
  1376. // what makes the operation actually safe.
  1377. $extra_excluded = array();
  1378. $termmeta_ids = $wpdb->get_col(
  1379. "SELECT DISTINCT meta_value FROM {$wpdb->termmeta}
  1380. WHERE meta_key = 'thumbnail_id'
  1381. AND meta_value > 0"
  1382. );
  1383. foreach ($termmeta_ids as $tm_id) {
  1384. $tm_id = (int) $tm_id;
  1385. if ($tm_id) { $extra_excluded[$tm_id] = true; }
  1386. }
  1387. foreach (array(
  1388. (int) get_theme_mod('custom_logo'),
  1389. (int) get_option('site_icon'),
  1390. ) as $cust_id) {
  1391. if ($cust_id) { $extra_excluded[$cust_id] = true; }
  1392. }
  1393. $hdr = get_theme_mod('header_image_data');
  1394. if (is_object($hdr) && !empty($hdr->attachment_id)) {
  1395. $extra_excluded[(int) $hdr->attachment_id] = true;
  1396. }
  1397. if (!empty($extra_excluded)) {
  1398. $media_ids = array_diff($media_ids, array_keys($extra_excluded));
  1399. }
  1400. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files');
  1401. return array_values($media_ids);
  1402. }
  1403. /**
  1404. * Handle AJAX remove unassigned media request (get IDs)
  1405. */
  1406. public function handle_remove_unassigned_media_ajax() {
  1407. while (ob_get_level()) {
  1408. ob_end_clean();
  1409. }
  1410. ob_start();
  1411. $original_error_reporting = error_reporting();
  1412. error_reporting(0);
  1413. error_log('STUDIOU WC MEDIA: Remove unassigned media AJAX handler called');
  1414. try {
  1415. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1416. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1417. return;
  1418. }
  1419. if (!current_user_can('manage_woocommerce')) {
  1420. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1421. return;
  1422. }
  1423. $media_ids = $this->get_unassigned_unused_media_ids();
  1424. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files to delete');
  1425. ob_clean();
  1426. wp_send_json_success(array(
  1427. 'media_ids' => $media_ids,
  1428. 'total_count' => count($media_ids),
  1429. 'message' => sprintf(
  1430. __('Found %d unused uncategorized media files to delete', 'studiou-wc-product-cat-manage'),
  1431. count($media_ids)
  1432. )
  1433. ));
  1434. } catch (Exception $e) {
  1435. error_log('STUDIOU WC MEDIA: Remove unassigned media failed - ' . $e->getMessage());
  1436. ob_clean();
  1437. wp_send_json_error(array(
  1438. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1439. ));
  1440. } finally {
  1441. error_reporting($original_error_reporting);
  1442. ob_end_clean();
  1443. }
  1444. }
  1445. /**
  1446. * Handle AJAX remove unassigned media batch request
  1447. */
  1448. public function handle_remove_unassigned_media_batch_ajax() {
  1449. while (ob_get_level()) {
  1450. ob_end_clean();
  1451. }
  1452. ob_start();
  1453. $original_error_reporting = error_reporting();
  1454. error_reporting(0);
  1455. error_log('STUDIOU WC MEDIA: Remove unassigned media batch AJAX handler called');
  1456. try {
  1457. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1458. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1459. return;
  1460. }
  1461. if (!current_user_can('manage_woocommerce')) {
  1462. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1463. return;
  1464. }
  1465. if (!isset($_POST['media_ids'])) {
  1466. wp_send_json_error(array('message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')));
  1467. return;
  1468. }
  1469. $media_ids = array_map('intval', $_POST['media_ids']);
  1470. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' unassigned media for deletion');
  1471. $result = $this->delete_media_batch($media_ids);
  1472. error_log('STUDIOU WC MEDIA: Unassigned batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1473. ob_clean();
  1474. wp_send_json_success(array(
  1475. 'deleted_count' => $result['deleted_count'],
  1476. 'failed_count' => $result['failed_count'],
  1477. 'failed_media' => $result['failed_media']
  1478. ));
  1479. } catch (Exception $e) {
  1480. error_log('STUDIOU WC MEDIA: Unassigned media batch failed - ' . $e->getMessage());
  1481. ob_clean();
  1482. wp_send_json_error(array(
  1483. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1484. ));
  1485. } finally {
  1486. error_reporting($original_error_reporting);
  1487. ob_end_clean();
  1488. }
  1489. }
  1490. // ========================================================================
  1491. // Update Product Variant Prices (UPVP) — v1.5.3
  1492. // Bulk-update regular_price on product_variation records by category +
  1493. // attribute filter. Touches only product records; never order items, carts,
  1494. // or historical order data.
  1495. // ========================================================================
  1496. /**
  1497. * Get list of attribute "heads" usable for variations.
  1498. *
  1499. * Source 1: every wc_get_attribute_taxonomies() entry (global attributes)
  1500. * — key = 'pa_<slug>', is_taxonomy = true.
  1501. * Source 2: distinct meta_key starting with 'attribute_' on product_variation
  1502. * rows that are NOT global taxonomies (custom product-level
  1503. * attributes flagged for variations) — key = '<slug>',
  1504. * is_taxonomy = false.
  1505. *
  1506. * @return array [ ['key' => string, 'label' => string, 'is_taxonomy' => bool], ... ]
  1507. */
  1508. public function get_variation_attribute_heads() {
  1509. global $wpdb;
  1510. $heads = array();
  1511. $seen = array();
  1512. // Source 1: global taxonomies.
  1513. $taxonomies = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : array();
  1514. if (!empty($taxonomies)) {
  1515. foreach ($taxonomies as $tax) {
  1516. $key = 'pa_' . $tax->attribute_name;
  1517. if (isset($seen[$key])) {
  1518. continue;
  1519. }
  1520. $seen[$key] = true;
  1521. $heads[] = array(
  1522. 'key' => $key,
  1523. 'label' => !empty($tax->attribute_label) ? $tax->attribute_label : $tax->attribute_name,
  1524. 'is_taxonomy' => true,
  1525. );
  1526. }
  1527. }
  1528. // Source 2: existing variation postmeta (attribute_*).
  1529. $sql = "
  1530. SELECT DISTINCT pm.meta_key
  1531. FROM {$wpdb->postmeta} pm
  1532. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1533. WHERE v.post_type = 'product_variation'
  1534. AND v.post_status IN ('publish','private')
  1535. AND pm.meta_key LIKE %s
  1536. ";
  1537. $rows = $wpdb->get_col($wpdb->prepare($sql, $wpdb->esc_like('attribute_') . '%'));
  1538. if (!empty($rows)) {
  1539. foreach ($rows as $meta_key) {
  1540. $slug = substr($meta_key, strlen('attribute_'));
  1541. if ($slug === '' || isset($seen[$slug])) {
  1542. continue;
  1543. }
  1544. $seen[$slug] = true;
  1545. $heads[] = array(
  1546. 'key' => $slug,
  1547. 'label' => wc_attribute_label($slug),
  1548. 'is_taxonomy' => (strpos($slug, 'pa_') === 0) || taxonomy_exists($slug),
  1549. );
  1550. }
  1551. }
  1552. // Source 3: variable parent products' _product_attributes postmeta.
  1553. // Catches attributes flagged "Used for variations" on the product's
  1554. // Attributes tab, even when (a) the attribute is a custom non-global
  1555. // entry, or (b) no variations have been generated yet.
  1556. $sql_parents = "
  1557. SELECT pm.meta_value
  1558. FROM {$wpdb->postmeta} pm
  1559. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1560. WHERE p.post_type = 'product'
  1561. AND p.post_status IN ('publish','private','draft')
  1562. AND pm.meta_key = '_product_attributes'
  1563. ";
  1564. $serialized_rows = $wpdb->get_col($sql_parents);
  1565. if (!empty($serialized_rows)) {
  1566. foreach ($serialized_rows as $serialized) {
  1567. $attrs = maybe_unserialize($serialized);
  1568. if (!is_array($attrs)) {
  1569. continue;
  1570. }
  1571. foreach ($attrs as $attr_key => $attr_data) {
  1572. if (!is_array($attr_data) || empty($attr_data['is_variation'])) {
  1573. continue;
  1574. }
  1575. $is_taxonomy = !empty($attr_data['is_taxonomy']);
  1576. $name = isset($attr_data['name']) ? $attr_data['name'] : $attr_key;
  1577. $key = $is_taxonomy ? $name : sanitize_title($name);
  1578. if ($key === '' || isset($seen[$key])) {
  1579. continue;
  1580. }
  1581. $seen[$key] = true;
  1582. $heads[] = array(
  1583. 'key' => $key,
  1584. 'label' => $is_taxonomy ? wc_attribute_label($key) : $name,
  1585. 'is_taxonomy' => $is_taxonomy,
  1586. );
  1587. }
  1588. }
  1589. }
  1590. // Sort alphabetically by label.
  1591. usort($heads, function($a, $b) {
  1592. return strcasecmp($a['label'], $b['label']);
  1593. });
  1594. return $heads;
  1595. }
  1596. /**
  1597. * Get distinct values for the given attribute key, scoped to existing
  1598. * variations (and optionally to a set of parent product categories).
  1599. *
  1600. * For taxonomy attributes (pa_*) the meta_value is the term slug; we
  1601. * resolve labels via get_term_by('slug', ..., $taxonomy).
  1602. *
  1603. * @param string $attribute_key E.g. 'pa_color' or 'size'.
  1604. * @param int[] $category_ids Optional list of parent product_cat term IDs.
  1605. * @return array [ ['value' => string, 'label' => string], ... ]
  1606. */
  1607. public function get_variation_attribute_values($attribute_key, $category_ids = array()) {
  1608. global $wpdb;
  1609. $attribute_key = sanitize_text_field($attribute_key);
  1610. if ($attribute_key === '') {
  1611. return array();
  1612. }
  1613. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1614. $params = array($meta_key);
  1615. $cat_join = '';
  1616. $cat_where = '';
  1617. if (!empty($category_ids)) {
  1618. $cat_ids = array_map('intval', $category_ids);
  1619. $cat_ids = array_filter($cat_ids, function($v) { return $v > 0; });
  1620. if (!empty($cat_ids)) {
  1621. $placeholders = implode(',', array_fill(0, count($cat_ids), '%d'));
  1622. $cat_join = "
  1623. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1624. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1625. ";
  1626. $cat_where = "
  1627. AND tt.taxonomy = 'product_cat'
  1628. AND tt.term_id IN ($placeholders)
  1629. ";
  1630. $params = array_merge($params, $cat_ids);
  1631. }
  1632. }
  1633. $sql = "
  1634. SELECT DISTINCT pm.meta_value
  1635. FROM {$wpdb->postmeta} pm
  1636. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1637. AND v.post_type = 'product_variation'
  1638. AND v.post_status IN ('publish','private')
  1639. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1640. AND p.post_type = 'product'
  1641. $cat_join
  1642. WHERE pm.meta_key = %s
  1643. AND pm.meta_value <> ''
  1644. $cat_where
  1645. ";
  1646. $values = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1647. $is_taxonomy = (strpos($attribute_key, 'pa_') === 0) || taxonomy_exists($attribute_key);
  1648. // Fallback: if SQL returned no values but the attribute exists on a
  1649. // variable parent's _product_attributes (e.g. variations not generated
  1650. // yet, or custom attribute), parse pipe-separated values from there.
  1651. if (empty($values)) {
  1652. $sanitized_key = $is_taxonomy
  1653. ? (strpos($attribute_key, 'pa_') === 0 ? $attribute_key : 'pa_' . $attribute_key)
  1654. : sanitize_title($attribute_key);
  1655. $sql_parents = "
  1656. SELECT pm.meta_value
  1657. FROM {$wpdb->postmeta} pm
  1658. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1659. WHERE p.post_type = 'product'
  1660. AND p.post_status IN ('publish','private','draft')
  1661. AND pm.meta_key = '_product_attributes'
  1662. ";
  1663. $rows = $wpdb->get_col($sql_parents);
  1664. $values = array();
  1665. if (!empty($rows)) {
  1666. foreach ($rows as $serialized) {
  1667. $attrs = maybe_unserialize($serialized);
  1668. if (!is_array($attrs) || !isset($attrs[$sanitized_key])) {
  1669. continue;
  1670. }
  1671. $entry = $attrs[$sanitized_key];
  1672. if (empty($entry['is_variation'])) {
  1673. continue;
  1674. }
  1675. if ($is_taxonomy) {
  1676. // Taxonomy custom values are stored as term IDs in 'value'.
  1677. $term_ids = !empty($entry['value']) ? wp_parse_id_list($entry['value']) : array();
  1678. if (empty($term_ids)) {
  1679. // Or the parent uses all terms — pull them from the taxonomy.
  1680. $tax_name = $sanitized_key;
  1681. $terms = get_terms(array('taxonomy' => $tax_name, 'hide_empty' => false));
  1682. if (!is_wp_error($terms)) {
  1683. foreach ($terms as $t) {
  1684. $values[] = $t->slug;
  1685. }
  1686. }
  1687. } else {
  1688. foreach ($term_ids as $tid) {
  1689. $term = get_term($tid, $sanitized_key);
  1690. if ($term && !is_wp_error($term)) {
  1691. $values[] = $term->slug;
  1692. }
  1693. }
  1694. }
  1695. } else {
  1696. $raw = isset($entry['value']) ? (string) $entry['value'] : '';
  1697. if ($raw !== '') {
  1698. $parts = array_map('trim', explode('|', $raw));
  1699. foreach ($parts as $p) {
  1700. if ($p !== '') {
  1701. $values[] = $p;
  1702. }
  1703. }
  1704. }
  1705. }
  1706. }
  1707. $values = array_values(array_unique($values));
  1708. }
  1709. }
  1710. if (empty($values)) {
  1711. return array();
  1712. }
  1713. $result = array();
  1714. foreach ($values as $value) {
  1715. $label = $value;
  1716. if ($is_taxonomy) {
  1717. $tax = (strpos($attribute_key, 'pa_') === 0) ? $attribute_key : 'pa_' . $attribute_key;
  1718. $term = get_term_by('slug', $value, $tax);
  1719. if ($term && !is_wp_error($term)) {
  1720. $label = $term->name;
  1721. }
  1722. }
  1723. $result[] = array(
  1724. 'value' => $value,
  1725. 'label' => $label,
  1726. );
  1727. }
  1728. usort($result, function($a, $b) {
  1729. return strcasecmp($a['label'], $b['label']);
  1730. });
  1731. return $result;
  1732. }
  1733. /**
  1734. * Find variations matching the filter.
  1735. *
  1736. * @param int[] $category_ids
  1737. * @param string $attribute_key
  1738. * @param string $attribute_value
  1739. * @return array ['count' => int, 'ids' => int[], 'sample' => array[]]
  1740. */
  1741. public function find_matching_variations($category_ids, $attribute_key, $attribute_value) {
  1742. global $wpdb;
  1743. $category_ids = array_filter(array_map('intval', (array) $category_ids), function($v) { return $v > 0; });
  1744. $attribute_key = sanitize_text_field($attribute_key);
  1745. $attribute_value = sanitize_text_field($attribute_value);
  1746. if (empty($category_ids) || $attribute_key === '' || $attribute_value === '') {
  1747. return array('count' => 0, 'ids' => array(), 'sample' => array());
  1748. }
  1749. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1750. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  1751. $sql = "
  1752. SELECT DISTINCT v.ID
  1753. FROM {$wpdb->posts} v
  1754. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1755. INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = v.ID
  1756. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1757. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1758. WHERE v.post_type = 'product_variation'
  1759. AND v.post_status IN ('publish','private')
  1760. AND p.post_type = 'product'
  1761. AND tt.taxonomy = 'product_cat'
  1762. AND tt.term_id IN ($placeholders)
  1763. AND pm.meta_key = %s
  1764. AND pm.meta_value = %s
  1765. ";
  1766. $params = array_merge($category_ids, array($meta_key, $attribute_value));
  1767. $ids = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1768. $ids = $ids ? array_map('intval', $ids) : array();
  1769. // Build a sample (up to 20).
  1770. $sample = array();
  1771. $slice = array_slice($ids, 0, 20);
  1772. foreach ($slice as $id) {
  1773. $variation = wc_get_product($id);
  1774. if (!$variation) {
  1775. continue;
  1776. }
  1777. $parent_id = $variation->get_parent_id();
  1778. $parent_name = '';
  1779. if ($parent_id) {
  1780. $parent = wc_get_product($parent_id);
  1781. if ($parent) {
  1782. $parent_name = $parent->get_name();
  1783. }
  1784. }
  1785. $sample[] = array(
  1786. 'id' => $id,
  1787. 'sku' => $variation->get_sku(),
  1788. 'name' => $variation->get_name(),
  1789. 'parent_name' => $parent_name,
  1790. 'current_price' => $variation->get_regular_price(),
  1791. );
  1792. }
  1793. return array(
  1794. 'count' => count($ids),
  1795. 'ids' => $ids,
  1796. 'sample' => $sample,
  1797. );
  1798. }
  1799. /**
  1800. * Apply new regular price to a list of variation IDs.
  1801. *
  1802. * @param int[] $variation_ids
  1803. * @param string $new_price
  1804. * @return array ['updated','failed','failed_ids','message']
  1805. */
  1806. public function apply_variant_price($variation_ids, $new_price) {
  1807. $variation_ids = array_filter(array_map('intval', (array) $variation_ids), function($v) { return $v > 0; });
  1808. // Validate price.
  1809. if (!is_numeric($new_price) || (float) $new_price < 0) {
  1810. return array(
  1811. 'updated' => 0,
  1812. 'failed' => 0,
  1813. 'failed_ids' => array(),
  1814. 'message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage'),
  1815. 'error' => true,
  1816. );
  1817. }
  1818. $formatted = wc_format_decimal($new_price);
  1819. $new_price_f = (float) $formatted;
  1820. $updated = 0;
  1821. $failed = 0;
  1822. $failed_ids = array();
  1823. $parent_ids = array();
  1824. // v1.7.1 — L7: collect variations whose existing sale_price is higher
  1825. // than the new regular_price. We don't auto-clamp (sale data is
  1826. // operator-owned) but we surface the inconsistency so the operator
  1827. // can fix it. Returned in the response so the UI can show it.
  1828. $sale_warnings = array();
  1829. foreach ($variation_ids as $id) {
  1830. try {
  1831. $variation = wc_get_product($id);
  1832. if (!$variation || !$variation->is_type('variation')) {
  1833. $failed++;
  1834. $failed_ids[] = $id;
  1835. error_log('STUDIOU WC UPVP: Variation ' . $id . ' not found or not a variation');
  1836. continue;
  1837. }
  1838. $sale_price_raw = $variation->get_sale_price();
  1839. if ($sale_price_raw !== '' && $sale_price_raw !== null) {
  1840. $sale_f = (float) $sale_price_raw;
  1841. if ($sale_f > $new_price_f) {
  1842. error_log(sprintf(
  1843. 'STUDIOU WC UPVP: variation %d has sale_price %s greater than new regular_price %s — sale > regular after update; review needed',
  1844. $id, $sale_price_raw, $formatted
  1845. ));
  1846. $sale_warnings[] = array(
  1847. 'id' => $id,
  1848. 'sale_price' => $sale_price_raw,
  1849. 'new_regular' => $formatted,
  1850. );
  1851. }
  1852. }
  1853. $variation->set_regular_price($formatted);
  1854. $variation->save();
  1855. $updated++;
  1856. $parent_id = $variation->get_parent_id();
  1857. if ($parent_id) {
  1858. $parent_ids[$parent_id] = true;
  1859. }
  1860. } catch (Exception $e) {
  1861. $failed++;
  1862. $failed_ids[] = $id;
  1863. error_log('STUDIOU WC UPVP: Exception updating variation ' . $id . ' - ' . $e->getMessage());
  1864. }
  1865. }
  1866. // Re-sync parent variable products so price-range cache reflects the new prices.
  1867. if (!empty($parent_ids) && class_exists('WC_Product_Variable')) {
  1868. foreach (array_keys($parent_ids) as $parent_id) {
  1869. try {
  1870. WC_Product_Variable::sync($parent_id);
  1871. if (function_exists('wc_delete_product_transients')) {
  1872. wc_delete_product_transients($parent_id);
  1873. }
  1874. } catch (Exception $e) {
  1875. error_log('STUDIOU WC UPVP: Failed to sync parent ' . $parent_id . ' - ' . $e->getMessage());
  1876. }
  1877. }
  1878. }
  1879. $message = sprintf(
  1880. __('Successfully updated %d variations.', 'studiou-wc-product-cat-manage'),
  1881. $updated
  1882. );
  1883. if ($failed > 0) {
  1884. $message .= ' ' . sprintf(
  1885. __('Failed to update %d variations.', 'studiou-wc-product-cat-manage'),
  1886. $failed
  1887. );
  1888. }
  1889. if (!empty($sale_warnings)) {
  1890. $message .= ' ' . sprintf(
  1891. /* translators: %d: number of variations whose existing sale_price is now greater than the new regular_price */
  1892. __('Warning: %d variations have a sale price greater than the new regular price (sale > regular). Review the variations and adjust the sale price.', 'studiou-wc-product-cat-manage'),
  1893. count($sale_warnings)
  1894. );
  1895. }
  1896. return array(
  1897. 'updated' => $updated,
  1898. 'failed' => $failed,
  1899. 'failed_ids' => $failed_ids,
  1900. 'sale_warnings' => $sale_warnings,
  1901. 'message' => $message,
  1902. );
  1903. }
  1904. /**
  1905. * Common AJAX preflight: nonce + capability + output buffer setup.
  1906. * Returns false on failure (after sending JSON error), true on success.
  1907. */
  1908. private function upvp_preflight() {
  1909. while (ob_get_level()) {
  1910. ob_end_clean();
  1911. }
  1912. ob_start();
  1913. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1914. ob_clean();
  1915. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1916. return false;
  1917. }
  1918. if (!current_user_can('manage_woocommerce')) {
  1919. ob_clean();
  1920. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1921. return false;
  1922. }
  1923. return true;
  1924. }
  1925. /**
  1926. * AJAX: list variation attribute heads.
  1927. */
  1928. public function handle_upvp_get_attributes_ajax() {
  1929. if (!$this->upvp_preflight()) return;
  1930. $original_error_reporting = error_reporting();
  1931. error_reporting(0);
  1932. try {
  1933. $heads = $this->get_variation_attribute_heads();
  1934. ob_clean();
  1935. wp_send_json_success(array('attributes' => $heads));
  1936. } catch (Exception $e) {
  1937. error_log('STUDIOU WC UPVP: get_attributes failed - ' . $e->getMessage());
  1938. ob_clean();
  1939. wp_send_json_error(array('message' => $e->getMessage()));
  1940. } finally {
  1941. error_reporting($original_error_reporting);
  1942. ob_end_clean();
  1943. }
  1944. }
  1945. /**
  1946. * AJAX: list values for the chosen attribute (scoped to selected categories).
  1947. */
  1948. public function handle_upvp_get_attribute_values_ajax() {
  1949. if (!$this->upvp_preflight()) return;
  1950. $original_error_reporting = error_reporting();
  1951. error_reporting(0);
  1952. try {
  1953. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1954. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1955. if ($attribute_key === '') {
  1956. ob_clean();
  1957. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1958. return;
  1959. }
  1960. $values = $this->get_variation_attribute_values($attribute_key, $category_ids);
  1961. ob_clean();
  1962. wp_send_json_success(array('values' => $values));
  1963. } catch (Exception $e) {
  1964. error_log('STUDIOU WC UPVP: get_attribute_values failed - ' . $e->getMessage());
  1965. ob_clean();
  1966. wp_send_json_error(array('message' => $e->getMessage()));
  1967. } finally {
  1968. error_reporting($original_error_reporting);
  1969. ob_end_clean();
  1970. }
  1971. }
  1972. /**
  1973. * AJAX: count + sample of variations matching the current filter.
  1974. */
  1975. public function handle_upvp_count_ajax() {
  1976. if (!$this->upvp_preflight()) return;
  1977. $original_error_reporting = error_reporting();
  1978. error_reporting(0);
  1979. try {
  1980. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1981. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1982. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  1983. if (empty($category_ids)) {
  1984. ob_clean();
  1985. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  1986. return;
  1987. }
  1988. if ($attribute_key === '') {
  1989. ob_clean();
  1990. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1991. return;
  1992. }
  1993. if ($attribute_value === '') {
  1994. ob_clean();
  1995. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  1996. return;
  1997. }
  1998. $result = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  1999. ob_clean();
  2000. wp_send_json_success(array(
  2001. 'count' => $result['count'],
  2002. 'sample' => $result['sample'],
  2003. ));
  2004. } catch (Exception $e) {
  2005. error_log('STUDIOU WC UPVP: count failed - ' . $e->getMessage());
  2006. ob_clean();
  2007. wp_send_json_error(array('message' => $e->getMessage()));
  2008. } finally {
  2009. error_reporting($original_error_reporting);
  2010. ob_end_clean();
  2011. }
  2012. }
  2013. /**
  2014. * AJAX: apply new regular price to all matching variations.
  2015. */
  2016. public function handle_upvp_apply_ajax() {
  2017. if (!$this->upvp_preflight()) return;
  2018. $original_error_reporting = error_reporting();
  2019. error_reporting(0);
  2020. try {
  2021. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  2022. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  2023. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  2024. $new_price = isset($_POST['new_price']) ? sanitize_text_field(wp_unslash($_POST['new_price'])) : '';
  2025. if (empty($category_ids)) {
  2026. ob_clean();
  2027. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  2028. return;
  2029. }
  2030. if ($attribute_key === '' || $attribute_value === '') {
  2031. ob_clean();
  2032. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  2033. return;
  2034. }
  2035. if ($new_price === '' || !is_numeric($new_price) || (float) $new_price < 0) {
  2036. ob_clean();
  2037. wp_send_json_error(array('message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage')));
  2038. return;
  2039. }
  2040. $matching = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  2041. if ($matching['count'] === 0) {
  2042. ob_clean();
  2043. wp_send_json_error(array('message' => __('No variations match the current filter.', 'studiou-wc-product-cat-manage')));
  2044. return;
  2045. }
  2046. $result = $this->apply_variant_price($matching['ids'], $new_price);
  2047. ob_clean();
  2048. wp_send_json_success(array(
  2049. 'updated' => $result['updated'],
  2050. 'failed' => $result['failed'],
  2051. 'failed_ids' => $result['failed_ids'],
  2052. 'message' => $result['message'],
  2053. ));
  2054. } catch (Exception $e) {
  2055. error_log('STUDIOU WC UPVP: apply failed - ' . $e->getMessage());
  2056. ob_clean();
  2057. wp_send_json_error(array('message' => $e->getMessage()));
  2058. } finally {
  2059. error_reporting($original_error_reporting);
  2060. ob_end_clean();
  2061. }
  2062. }
  2063. }