'POST', 'callback' => 'addifect_set_active_kit_connection', 'permission_callback' => 'addifect_can_edit_designs', 'args' => array( 'kit_id' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_key', ), 'design_id' => array( 'type' => 'integer', 'required' => true, ), ), ) ); } ); /** * Save the Kit Connection Mapping. * Links a Kit to a specific Design Post ID and flushes * stale transients associated with the previous design context. * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ function addifect_set_active_kit_connection( WP_REST_Request $request ) { $new_kit_id = $request->get_param( 'kit_id' ); $new_design_id = (int) $request->get_param( 'design_id' ); // 1. Cleanup using the EXISTING session index before we overwrite it $current_session = get_transient( 'addifect_active_session_index' ); if ( is_array( $current_session ) && isset( $current_session['all_keys'] ) ) { foreach ( (array) $current_session['all_keys'] as $tid ) { delete_transient( 'addifect_site_template_' . $tid ); } } // 2. Update Connection Source of Truth update_option( 'addifect_active_connection', array( 'kit_id' => $new_kit_id, 'design_id' => $new_design_id, 'last_sync' => time(), ) ); // 3. Prime the NEW session index from the Master Meta $master_index = get_post_meta( $new_design_id, '_addifect_design_index', true ); if ( ! is_array( $master_index ) ) { $master_index = array(); } // Check if kit exists, if not initialize it. if ( ! isset( $master_index[ $new_kit_id ] ) ) { $master_index[ $new_kit_id ] = array( 'parts' => array(), 'all_keys' => array(), ); } /** * THE FIX: Force an 'updated' timestamp on switch. * This forces the localized script 'templatesUpdated' to change, * which busts the browser cache for the new kit immediately. */ $master_index[ $new_kit_id ]['updated'] = time(); // Update the Master Meta so the timestamp is permanent. update_post_meta( $new_design_id, '_addifect_design_index', $master_index ); // 4. Overwrite the single high-speed session index. delete_transient( 'addifect_active_session_index' ); set_transient( 'addifect_active_session_index', $master_index[ $new_kit_id ], 12 * HOUR_IN_SECONDS ); return new WP_REST_Response( array( 'success' => true, 'updated' => $master_index[ $new_kit_id ]['updated'], ), 200 ); }