├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── assets ├── banner-1544x500.jpg ├── banner-772x250.jpg ├── icon-128x128.jpg ├── icon-256x256.jpg ├── woocommerce-custom-orders-table-icon.psd └── woocommerce-custom-orders-table.psd ├── includes ├── Exceptions │ └── QueryException.php ├── Util │ └── QueryIterator.php ├── class-wc-customer-data-store-custom-table.php ├── class-wc-order-data-store-custom-table.php ├── class-wc-order-refund-data-store-custom-table.php ├── class-woocommerce-custom-orders-table-cli.php ├── class-woocommerce-custom-orders-table-filters.php ├── class-woocommerce-custom-orders-table-install.php └── class-woocommerce-custom-orders-table.php ├── readme.txt └── woocommerce-custom-orders-table.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | **Note:** Based on [our compatibility policy](CONTRIBUTING.md#compatibility-policy), this plugin now requires WooCommerce 3.7 or higher. As such, PHP 5.6 or newer is also required. 11 | 12 | ### Added 13 | 14 | * Enable the migration WP-CLI commands to accept `--batch-size=0`, which disables batching ([#152], props @AlchemyUnited, @mfs-mindsize). 15 | 16 | ### Fixed 17 | 18 | * Change the plugin's display name from "WooCommerce - Custom Orders Table" to "WooCommerce Custom Orders Table" ([#138], props @jb510). 19 | * Add a `method_exists()` check to the wildcard `set_{$column}` method ([#139], props @blohbaugh). 20 | * Rewrite the way that WooCommerce core is installed in test environments ([#154]). 21 | * Use offsets to avoid infinite loops during migration ([#157], props @mfs-mindsize). 22 | * Only register the hooks for `WC_Customer_Data_Store_Custom_Table` once ([#164]). 23 | 24 | ## [Version 1.0.0 (Release Candidate 3)] - 2019-07-24 25 | 26 | * Ensure the orders query is adjusted as late as possible ([#126]). 27 | * Update the plugin license to GPLv3+ to match WooCommerce core ([#123]). 28 | * Define the compatibility policy for the plugin with regards to WordPress, WooCommerce, and PHP versions ([#120], [#127]). 29 | * Introduce PHPStan for static code analysis ([#116], [#117], props @szepeviktor). 30 | * Refresh and update Composer configuration and dependencies ([#121], [#124]). 31 | 32 | ## [Version 1.0.0 (Release Candidate 2)] - 2018-12-14 33 | 34 | * Reduced overhead of PHP autoloader ([#86], props @schlessera). 35 | * Converted the `customer_user_agent` column from `varchar(200)` to `text` ([#91]). 36 | * Fixed an issue where `empty()` was being called on a non-variable, which causes a fatal error in PHP < 5.5 ([#94]). 37 | * Prevented empty strings from being saved to the `order_key` column, which causes issues with the column's uniqueness constraint ([#101], props @crstauf). 38 | * Fixed an issue where *existing* invalid emails in the system were causing migration errors as they were re-saved ([#104]). 39 | * Updated Travis CI testing matrix to include WordPress 5.0 ([#103]). 40 | * Repaired the generation of code coverage reports for Coveralls ([#87], [#88]). 41 | 42 | ## [Version 1.0.0 (Release Candidate)] - 2018-09-25 43 | 44 | * Major refactoring of the WP-CLI migration commands ([#61], [#79], [#81]). 45 | * Database table optimizations ([#65], props @raunak-gupta). 46 | * Prevent duplicate IDs when saving orders and refunds ([#64]). 47 | * Ensure that order refunds are also stored in the custom orders table ([#52]). 48 | * Ensure the custom orders table is registered within WooCommerce ([#50]). 49 | * Resolve issue in CLI importer where a `false` value from `wc_get_order()` could cause a fatal error ([#43] & [#46], props @zacscott). 50 | * Fix bug where orders with the same post date could be handled in the wrong order during migration ([#84]). 51 | * Prevent customer notes from being deleted during migration ([#82]). 52 | * Bump the "WC tested up to" version to 3.5.0 ([#80]). 53 | * Major refactoring within the plugin test suite ([#51], [#53], [#60], [#72], [#78]). 54 | * Prevent Travis CI from using PHPUnit 7.0 [until the WordPress core test suite can support it, too](https://core.trac.wordpress.org/ticket/43218). 55 | 56 | [This release also restores the repo development history](https://github.com/liquidweb/woocommerce-custom-orders-table/pull/63) prior to [Version 1.0.0 (Beta 1)], ensuring that the team @Mindsize is credited appropriately for their work. 57 | 58 | ## [Version 1.0.0 (Beta 3)] - 2018-01-23 59 | 60 | * Plugin test suite now extends the WooCommerce core test suite, ensuring WooCommerce behaves as expected when the plugin is active ([#26]). 61 | * The custom data store now extends the `WC_Order_Data_Store_CPT` class, eliminating a lot of code duplication in the process ([#28]). 62 | - Includes areas that were previously missing, including reporting. 63 | - Plugin should now have 100% compatibility with default WooCommerce functionality. 64 | * Removed the dependency on a Composer-generated autoloader ([#36]). 65 | * Revert database columns to use `VARCHAR` types for compatibility with WordPress post meta tables. 66 | * Add table indexes on the `order_key`, `customer_id`, and `order_total` columns in the orders table ([#15]). 67 | * Refactor the WP-CLI command, including some changes to accepted arguments ([#35]) 68 | * Normalize the plugin name around "WooCommerce Custom Orders Table" ([#38]) 69 | * Added changelog and contributing documents ([#12]). 70 | * Massive improvements to test coverage and general WooCommerce compatibility. 71 | 72 | ## [Version 1.0.0 (Beta 2)] - 2017-12-22 73 | 74 | * Clean up codebase to adhere to the [WordPress coding standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/), and introduce an `.editorconfig` to make this kind of change less likely in the future ([#8]) 75 | * Introduced automated unit tests via the WordPress core test suite ([#9]) 76 | * Fixed bug where custom database table was not being created upon plugin activation ([#5], [#9]) 77 | * General documentation updates ([#2]) 78 | 79 | ## [Version 1.0.0 (Beta 1)] - 2017-10-02 80 | 81 | * Initial public release of the plugin in a beta state. 82 | 83 | 84 | [Unreleased]: https://github.com/liquidweb/woocommerce-custom-orders-table/compare/master...develop 85 | [Version 1.0.0 (Release Candidate 3)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-rc3 86 | [Version 1.0.0 (Release Candidate 2)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-rc2 87 | [Version 1.0.0 (Release Candidate)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-rc1 88 | [Version 1.0.0 (Beta 3)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-beta.3 89 | [Version 1.0.0 (Beta 2)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-beta.2 90 | [Version 1.0.0 (Beta 1)]: https://github.com/liquidweb/woocommerce-custom-orders-table/releases/tag/v1.0.0-beta.1 91 | [#2]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/2 92 | [#5]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/5 93 | [#8]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/8 94 | [#9]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/9 95 | [#12]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/12 96 | [#15]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/15 97 | [#26]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/26 98 | [#28]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/28 99 | [#35]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/35 100 | [#36]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/36 101 | [#38]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/38 102 | [#43]: https://github.com/liquidweb/woocommerce-custom-orders-table/issues/43 103 | [#46]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/46 104 | [#50]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/50 105 | [#51]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/51 106 | [#52]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/52 107 | [#53]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/53 108 | [#60]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/60 109 | [#61]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/61 110 | [#64]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/64 111 | [#65]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/65 112 | [#72]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/72 113 | [#78]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/78 114 | [#79]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/79 115 | [#80]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/80 116 | [#81]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/81 117 | [#82]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/82 118 | [#84]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/84 119 | [#86]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/86 120 | [#87]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/87 121 | [#88]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/88 122 | [#91]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/91 123 | [#94]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/94 124 | [#101]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/101 125 | [#103]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/103 126 | [#104]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/104 127 | [#116]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/116 128 | [#117]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/117 129 | [#120]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/120 130 | [#121]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/121 131 | [#123]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/123 132 | [#124]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/124 133 | [#126]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/126 134 | [#127]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/127 135 | [#138]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/138 136 | [#139]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/139 137 | [#152]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/152 138 | [#154]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/154 139 | [#157]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/157 140 | [#164]: https://github.com/liquidweb/woocommerce-custom-orders-table/pull/164 141 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WooCommerce Archive Orders Table 2 | 3 | This plugin can be used to archive orders older than 30 days to a separate orders table which helps to improve store's performance. There is absolutely no difference in how archived orders are displayed or accessed. However, the plugins relying on orders meta data won't be able to access data for the archived orders. 4 | 5 | This plugin is based on [LiquidWeb's Custom Orders Table](https://github.com/liquidweb/woocommerce-custom-orders-table). 6 | 7 | ## Requirements 8 | 9 | WooCommerce Custom Orders Table requires [WooCommerce 3.5.1 or newer](https://wordpress.org/plugins/woocommerce/). 10 | 11 | If you're looking to migrate existing order data, [you'll need to have the ability to run WP-CLI commands in your WooCommerce environment](http://wp-cli.org/). 12 | 13 | ## Migrating order data 14 | 15 | After installing and activating the plugin, you'll need to migrate orders from post meta into the newly-created orders table. 16 | 17 | The easiest way to accomplish this is via [WP-CLI](http://wp-cli.org/), and the plugin ships with five commands to help: 18 | 19 | ### Counting the orders to be migrated 20 | 21 | If you'd like to see the number of orders that have yet to be moved into the orders table, you can quickly retrieve this value with the `count` command: 22 | 23 | ``` 24 | $ wp wc orders-table count 25 | ``` 26 | 27 | #### Options 28 | 29 |
30 |
--duration=<no-of-days>
31 |
Set the duration of days, starting today, to skip archiving of orders.
32 |
For Ex: Setting this value to 45 will skip orders for the last 45 days from archiving.
33 |
34 | 35 | ### Analysing extra meta keys added by plugins 36 | 37 | The first step in the migration process is to analyse the extra meta keys added by the plugins based on which additional columns are created in the orders table. 38 | 39 | ``` 40 | $ wp wc orders-table optimize 41 | ``` 42 | 43 | ### Creating columns in the table for additional meta keys 44 | 45 | The `populate` command creates the additional columns in the database to accomodate data for the additional meta keys associated with the orders data. 46 | 47 | ``` 48 | $ wp wc orders-table populate 49 | ``` 50 | 51 | ### Migrate order data from post meta to the orders table 52 | 53 | The `migrate` command will flatten all post meta values for WooCommerce orders into a flat database table, optimized for performance. 54 | 55 | ``` 56 | $ wp wc orders-table migrate 57 | ``` 58 | 59 | Orders are queried in batches (determined via the `--batch-size` option) in order to reduce the memory footprint of the command (e.g. "only retrieve `$size` orders at a time"). Some environments may require a lower value than the default of 100. 60 | 61 | **Please note** that `migrate` will delete the original order post meta rows after a successful migration. If you want to preserve these, include the `--save-post-meta` flag! 62 | 63 | #### Options 64 | 65 |
66 |
--batch-size=<size>
67 |
The number of orders to process in each batch. Default is 100 orders per batch.
68 |
Passing `--batch-size=0` will disable batching.
69 |
--duration=<no-of-days>
70 |
Set the duration of days, starting today, to skip archiving of orders.
71 |
For Ex: Setting this value to 45 will skip orders for the last 45 days from archiving.
72 |
--save-post-meta
73 |
Preserve the original post meta after a successful migration. Default behavior is to clean up post meta.
74 |
75 | 76 | 77 | ### Copying data from the orders table into post meta 78 | 79 | If you require the post meta fields to be present (or are removing the custom orders table plugin), you may rollback the migration at any time with the `backfill` command. 80 | 81 | ``` 82 | $ wp wc orders-table backfill 83 | ``` 84 | 85 | This command does the opposite of `migrate`, looping through the orders table and saving each column into the corresponding post meta key. Be aware that this may dramatically increase the size of your post meta table! 86 | 87 | #### Options 88 | 89 |
90 |
--batch-size=<size>
91 |
The number of orders to process in each batch. Default is 100 orders per batch.
92 |
Passing `--batch-size=0` will disable batching.
93 |
94 | -------------------------------------------------------------------------------- /assets/banner-1544x500.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/banner-1544x500.jpg -------------------------------------------------------------------------------- /assets/banner-772x250.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/banner-772x250.jpg -------------------------------------------------------------------------------- /assets/icon-128x128.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/icon-128x128.jpg -------------------------------------------------------------------------------- /assets/icon-256x256.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/icon-256x256.jpg -------------------------------------------------------------------------------- /assets/woocommerce-custom-orders-table-icon.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/woocommerce-custom-orders-table-icon.psd -------------------------------------------------------------------------------- /assets/woocommerce-custom-orders-table.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/woocart/woocommerce-archive-orders-table/d64b78083938be7c750f6d7e7f33dd07db433842/assets/woocommerce-custom-orders-table.psd -------------------------------------------------------------------------------- /includes/Exceptions/QueryException.php: -------------------------------------------------------------------------------- 1 | query = $query; 101 | $this->chunk_size = $chunk_size; 102 | $this->db = $GLOBALS['wpdb']; 103 | 104 | // Swap the SELECT clause for SELECT COUNT(*). 105 | $this->count_query = preg_replace( '/^.*? FROM /', 'SELECT COUNT(*) FROM ', $query, 1, $replacements ); 106 | 107 | // If we haven't found anything, assume we can't count. 108 | if ( 1 !== $replacements ) { 109 | $this->count_query = ''; 110 | } 111 | } 112 | 113 | /** 114 | * Count the total number of query results. 115 | * 116 | * @return int 117 | */ 118 | public function count() { 119 | $this->row_count = (int) $this->db->get_var( $this->count_query ); 120 | 121 | return $this->row_count; 122 | } 123 | 124 | /** 125 | * Get the current element. 126 | * 127 | * @return object An object representing the current row. 128 | */ 129 | public function current() { 130 | return $this->results[ $this->index_in_results ]; 131 | } 132 | 133 | /** 134 | * Get the current element's key. 135 | * 136 | * @return int 137 | */ 138 | public function key() { 139 | return $this->global_index; 140 | } 141 | 142 | /** 143 | * Advance the iterator. 144 | */ 145 | public function next() { 146 | $this->index_in_results++; 147 | $this->global_index++; 148 | } 149 | 150 | /** 151 | * Reset everything. 152 | */ 153 | public function rewind() { 154 | $this->results = []; 155 | $this->global_index = 0; 156 | $this->index_in_results = 0; 157 | $this->offset = 0; 158 | $this->depleted = false; 159 | } 160 | 161 | /** 162 | * Check if the current position is valid. 163 | * 164 | * If no query data has yet been loaded (or we've already looped through it), the next set of 165 | * results will be loaded from the database. 166 | * 167 | * @return bool 168 | */ 169 | public function valid() { 170 | if ( $this->depleted ) { 171 | return false; 172 | } 173 | 174 | // If we don't yet have the data, query the database. 175 | if ( ! isset( $this->results[ $this->index_in_results ] ) ) { 176 | $items_loaded = $this->load_items_from_db(); 177 | 178 | // Nothing came back, so we've reached the end. 179 | if ( ! $items_loaded ) { 180 | $this->rewind(); 181 | $this->depleted = true; 182 | return false; 183 | } 184 | 185 | $this->index_in_results = 0; 186 | } 187 | 188 | return true; 189 | } 190 | 191 | /** 192 | * Reduces the offset when the query row count shrinks 193 | * 194 | * In cases where the iterated rows are being updated such that they will no 195 | * longer be returned by the original query, the offset must be reduced to 196 | * iterate over all remaining rows. 197 | */ 198 | private function adjust_offset_for_shrinking_result_set() { 199 | if ( empty( $this->count_query ) ) { 200 | return; 201 | } 202 | 203 | $row_count = $this->db->get_var( $this->count_query ); 204 | 205 | // We have fewer rows than the last time we counted. 206 | if ( $row_count < $this->row_count ) { 207 | $this->offset -= $this->row_count - $row_count; 208 | } 209 | 210 | $this->row_count = $row_count; 211 | } 212 | 213 | /** 214 | * Retrieve the next chunk of results from the database. 215 | * 216 | * @throws QueryException When a database error is encountered. 217 | * 218 | * @return bool True if results were loaded, false otherwise. 219 | */ 220 | private function load_items_from_db() { 221 | $this->adjust_offset_for_shrinking_result_set(); 222 | 223 | $this->results = $this->db->get_results( 224 | $this->query . sprintf( ' LIMIT %d OFFSET %d', $this->chunk_size, $this->offset ), 225 | OBJECT 226 | ); 227 | 228 | if ( ! $this->results ) { 229 | if ( $this->db->last_error ) { 230 | throw new QueryException( 'Database error: ' . $this->db->last_error ); 231 | } 232 | 233 | return false; 234 | } 235 | 236 | $this->offset += $this->chunk_size; 237 | return true; 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /includes/class-wc-customer-data-store-custom-table.php: -------------------------------------------------------------------------------- 1 | get_last_order_meta( $customer ); 25 | 26 | if ( $last_order ) { 27 | return $last_order; 28 | } 29 | 30 | // $last_order is false, so we look for last_order in archive. 31 | return $this->get_last_order_archive( $customer ); 32 | } 33 | 34 | /** 35 | * Gets the customers last order from postmeta. 36 | * 37 | * @since 3.0.0 38 | * @param WC_Customer $customer Customer object. 39 | * @return WC_Order|false 40 | */ 41 | public function get_last_order_meta( $customer ) { 42 | $last_order = apply_filters( 43 | 'woocommerce_customer_get_last_order', 44 | get_user_meta( $customer->get_id(), '_last_order', true ), 45 | $customer 46 | ); 47 | 48 | if ( '' === $last_order ) { 49 | global $wpdb; 50 | 51 | $last_order = $wpdb->get_var( 52 | // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared 53 | "SELECT posts.ID 54 | FROM $wpdb->posts AS posts 55 | INNER JOIN {$wpdb->postmeta} AS meta on posts.ID = meta.post_id 56 | WHERE meta.meta_key = '_customer_user' 57 | AND meta.meta_value = '" . esc_sql( $customer->get_id() ) . "' 58 | AND posts.post_type = 'shop_order' 59 | AND posts.post_status IN ( '" . implode( "','", array_map( 'esc_sql', array_keys( wc_get_order_statuses() ) ) ) . "' ) 60 | ORDER BY posts.ID DESC" 61 | // phpcs:enable 62 | ); 63 | update_user_meta( $customer->get_id(), '_last_order', $last_order ); 64 | } 65 | 66 | if ( ! $last_order ) { 67 | return false; 68 | } 69 | 70 | return wc_get_order( absint( $last_order ) ); 71 | } 72 | 73 | /** 74 | * Gets the customers last order from archived orders table. 75 | * 76 | * @global $wpdb 77 | * 78 | * @param WC_Customer $customer The WC_Customer object. 79 | * @return WC_Order|false The last order from this customer, or FALSE if the customer has not 80 | * made an order. 81 | */ 82 | public function get_last_order_archive( $customer ) { 83 | global $wpdb; 84 | 85 | $table = wc_custom_order_table()->get_table_name(); 86 | $statuses = wc_get_order_statuses(); 87 | $last_order = $wpdb->get_var( 88 | $wpdb->prepare( 89 | " 90 | SELECT posts.ID FROM $wpdb->posts AS posts 91 | LEFT JOIN " . esc_sql( $table ) . " AS meta on posts.ID = meta.order_id 92 | WHERE meta.customer_id = %d 93 | AND posts.post_type = 'shop_order' 94 | AND posts.post_status IN (" . implode( ', ', array_fill( 0, count( $statuses ), '%s' ) ) . ') 95 | ORDER BY posts.ID DESC LIMIT 1', 96 | array_merge( array( $customer->get_id() ), array_keys( $statuses ) ) 97 | ) 98 | ); 99 | 100 | return $last_order ? wc_get_order( (int) $last_order ) : false; 101 | } 102 | 103 | /** 104 | * Register callbacks when the data store is first instantiated. 105 | */ 106 | public static function add_hooks() { 107 | add_filter( 'woocommerce_pre_customer_bought_product', __CLASS__ . '::pre_customer_bought_product', 10, 4 ); 108 | 109 | // Handle deleting a customer from the database. 110 | add_action( 'deleted_user', __CLASS__ . '::reset_order_customer_id_on_deleted_user' ); 111 | remove_action( 'deleted_user', 'wc_reset_order_customer_id_on_deleted_user' ); 112 | } 113 | 114 | /** 115 | * Short-circuit the wc_customer_bought_product() function. 116 | * 117 | * @see wc_customer_bought_product() 118 | * 119 | * @global $wpdb 120 | * 121 | * @param bool $purchased Whether or not the customer has purchased the product. 122 | * @param string $customer_email Customer email to check. 123 | * @param int $user_id User ID to check. 124 | * @param int $product_id Product ID to check. 125 | * 126 | * @return bool|null Whether or not the customer has already purchased the given product ID. 127 | */ 128 | public static function pre_customer_bought_product( $purchased, $customer_email, $user_id, $product_id ) { 129 | global $wpdb; 130 | 131 | $transient_name = 'wc_cbp_' . md5( $customer_email . $user_id . WC_Cache_Helper::get_transient_version( 'orders' ) ); 132 | $result = get_transient( $transient_name ); 133 | 134 | if ( false === $result ) { 135 | $customer_data = array( $user_id ); 136 | 137 | if ( $user_id ) { 138 | $user = get_user_by( 'id', $user_id ); 139 | 140 | if ( isset( $user->user_email ) ) { 141 | $customer_data[] = $user->user_email; 142 | } 143 | } 144 | 145 | if ( is_email( $customer_email ) ) { 146 | $customer_data[] = $customer_email; 147 | } 148 | 149 | $customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) ); 150 | $statuses = array_map( 'self::prefix_wc_status', wc_get_is_paid_statuses() ); 151 | 152 | if ( 0 === count( $customer_data ) ) { 153 | /** 154 | * Instead of returning false, we return null so that the function 155 | * moves on to query the wp_postmeta table for the same. 156 | */ 157 | return null; 158 | } 159 | 160 | $table = wc_custom_order_table()->get_table_name(); 161 | $result = $wpdb->get_col( 162 | $wpdb->prepare( 163 | " 164 | SELECT im.meta_value FROM {$wpdb->posts} AS p 165 | INNER JOIN " . esc_sql( $table ) . " AS pm ON p.ID = pm.order_id 166 | INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id 167 | INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id 168 | WHERE p.post_status IN (" . implode( ', ', array_fill( 0, count( $statuses ), '%s' ) ) . ') 169 | AND ( 170 | pm.billing_email IN (' . implode( ', ', array_fill( 0, count( $customer_data ), '%s' ) ) . ') 171 | OR pm.customer_id IN (' . implode( ', ', array_fill( 0, count( $customer_data ), '%s' ) ) . ") 172 | ) 173 | AND im.meta_key IN ( '_product_id', '_variation_id' ) 174 | AND im.meta_value != 0", 175 | array_merge( $statuses, $customer_data, $customer_data ) 176 | ) 177 | ); 178 | $result = array_map( 'absint', $result ); 179 | 180 | set_transient( $transient_name, $result, DAY_IN_SECONDS * 30 ); 181 | } 182 | 183 | return in_array( (int) $product_id, $result, true ); 184 | } 185 | 186 | /** 187 | * Reset customer_id on orders when a user is deleted. 188 | * 189 | * @param int $user_id The ID of the deleted user. 190 | */ 191 | public static function reset_order_customer_id_on_deleted_user( $user_id ) { 192 | global $wpdb; 193 | 194 | $wpdb->update( 195 | wc_custom_order_table()->get_table_name(), 196 | array( 'customer_id' => 0 ), 197 | array( 'customer_id' => $user_id ) 198 | ); 199 | } 200 | 201 | /** 202 | * Helper function to prefix a status with 'wc-'. 203 | * 204 | * Statuses that already contain the prefix will be skipped. 205 | * 206 | * @param string $status The status to prefix. 207 | * 208 | * @return string The status with 'wc-' prefixed. 209 | */ 210 | public static function prefix_wc_status( $status ) { 211 | if ( 'wc-' === substr( $status, 0, 3 ) ) { 212 | return $status; 213 | } 214 | 215 | return 'wc-' . $status; 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /includes/class-wc-order-data-store-custom-table.php: -------------------------------------------------------------------------------- 1 | get_id(); 38 | 39 | parent::delete( $order, $args ); 40 | 41 | // Delete the database row if force_delete is true. 42 | if ( isset( $args['force_delete'] ) && $args['force_delete'] ) { 43 | $wpdb->delete( 44 | wc_custom_order_table()->get_table_name(), 45 | array( 46 | 'order_id' => $order_id, 47 | ) 48 | ); 49 | } 50 | } 51 | 52 | /** 53 | * Read order data from the custom orders table. 54 | * 55 | * @param WC_Order $order The order object, passed by reference. 56 | * @param object $post_object The post object. 57 | */ 58 | protected function read_order_data( &$order, $post_object ) { 59 | $data = $this->get_order_data_from_table( $order ); 60 | 61 | if ( ! empty( $data ) ) { 62 | $order->set_props( $data ); 63 | } else { 64 | /** 65 | * Removed automatic migration of data to custom table. 66 | * Instead, we try to fetch metadata normally from the table. 67 | */ 68 | $id = $order->get_id(); 69 | $data = array(); 70 | 71 | // Loop over internal postmeta properties. 72 | foreach ( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() as $key => $value ) { 73 | $data[ $key ] = get_post_meta( $id, $value, true ); 74 | } 75 | 76 | // Get post for additional notes passed by the customer. 77 | $post = get_post( $id ); 78 | $data['customer_note'] = $post->post_excerpt; 79 | 80 | $order->set_props( $data ); 81 | } 82 | } 83 | 84 | /** 85 | * Retrieve a single order from the database. 86 | * 87 | * @global $wpdb 88 | * 89 | * @param WC_Order $order The order object. 90 | * 91 | * @return array The order row, as an associative array. 92 | */ 93 | public function get_order_data_from_table( $order ) { 94 | global $wpdb; 95 | 96 | $table = wc_custom_order_table()->get_table_name(); 97 | $data = (array) $wpdb->get_row( 98 | $wpdb->prepare( 99 | 'SELECT * FROM ' . esc_sql( $table ) . ' WHERE order_id = %d LIMIT 1', 100 | $order->get_id() 101 | ), 102 | ARRAY_A 103 | ); 104 | 105 | // Return early if there's no matching row in the orders table. 106 | if ( empty( $data ) ) { 107 | return array(); 108 | } 109 | 110 | $post = get_post( $order->get_id() ); 111 | 112 | // Expand anything that might need assistance. 113 | if ( isset( $data['prices_include_tax'] ) ) { 114 | $data['prices_include_tax'] = wc_string_to_bool( $data['prices_include_tax'] ); 115 | } 116 | 117 | // Append additional data. 118 | $data['customer_note'] = $post->post_excerpt; 119 | 120 | return $data; 121 | } 122 | 123 | /** 124 | * Helper method that updates all the post meta for an order based on its settings in the 125 | * WC_Order class. 126 | * 127 | * @global $wpdb 128 | * 129 | * @param WC_Order $order The order object, passed by reference. 130 | */ 131 | protected function update_post_meta( &$order ) { 132 | global $wpdb; 133 | 134 | $table = wc_custom_order_table()->get_table_name(); 135 | $changes = array(); 136 | $order_key = $order->get_order_key( 'edit' ); 137 | $order_data = array( 138 | 'order_id' => $order->get_id(), 139 | 'order_key' => $order_key ? $order_key : null, 140 | 'customer_id' => $order->get_customer_id( 'edit' ), 141 | 'payment_method' => $order->get_payment_method( 'edit' ), 142 | 'payment_method_title' => $order->get_payment_method_title( 'edit' ), 143 | 'transaction_id' => $order->get_transaction_id( 'edit' ), 144 | 'customer_ip_address' => $order->get_customer_ip_address( 'edit' ), 145 | 'customer_user_agent' => $order->get_customer_user_agent( 'edit' ), 146 | 'created_via' => $order->get_created_via( 'edit' ), 147 | 'date_completed' => $order->get_date_completed( 'edit' ), 148 | 'date_paid' => $order->get_date_paid( 'edit' ), 149 | 'cart_hash' => $order->get_cart_hash( 'edit' ), 150 | 151 | 'billing_index' => implode( ' ', $order->get_address( 'billing' ) ), 152 | 'billing_first_name' => $order->get_billing_first_name( 'edit' ), 153 | 'billing_last_name' => $order->get_billing_last_name( 'edit' ), 154 | 'billing_company' => $order->get_billing_company( 'edit' ), 155 | 'billing_address_1' => $order->get_billing_address_1( 'edit' ), 156 | 'billing_address_2' => $order->get_billing_address_2( 'edit' ), 157 | 'billing_city' => $order->get_billing_city( 'edit' ), 158 | 'billing_state' => $order->get_billing_state( 'edit' ), 159 | 'billing_postcode' => $order->get_billing_postcode( 'edit' ), 160 | 'billing_country' => $order->get_billing_country( 'edit' ), 161 | 'billing_email' => $order->get_billing_email( 'edit' ), 162 | 'billing_phone' => $order->get_billing_phone( 'edit' ), 163 | 164 | 'shipping_index' => implode( ' ', $order->get_address( 'shipping' ) ), 165 | 'shipping_first_name' => $order->get_shipping_first_name( 'edit' ), 166 | 'shipping_last_name' => $order->get_shipping_last_name( 'edit' ), 167 | 'shipping_company' => $order->get_shipping_company( 'edit' ), 168 | 'shipping_address_1' => $order->get_shipping_address_1( 'edit' ), 169 | 'shipping_address_2' => $order->get_shipping_address_2( 'edit' ), 170 | 'shipping_city' => $order->get_shipping_city( 'edit' ), 171 | 'shipping_state' => $order->get_shipping_state( 'edit' ), 172 | 'shipping_postcode' => $order->get_shipping_postcode( 'edit' ), 173 | 'shipping_country' => $order->get_shipping_country( 'edit' ), 174 | 175 | 'discount_total' => $order->get_discount_total( 'edit' ), 176 | 'discount_tax' => $order->get_discount_tax( 'edit' ), 177 | 'shipping_total' => $order->get_shipping_total( 'edit' ), 178 | 'shipping_tax' => $order->get_shipping_tax( 'edit' ), 179 | 'cart_tax' => $order->get_cart_tax( 'edit' ), 180 | 'total' => $order->get_total( 'edit' ), 181 | 182 | 'version' => $order->get_version( 'edit' ), 183 | 'currency' => $order->get_currency( 'edit' ), 184 | 'prices_include_tax' => wc_bool_to_string( $order->get_prices_include_tax( 'edit' ) ), 185 | ); 186 | 187 | // Add additional metakeys data. 188 | $extra_metakeys = get_option( WC_CUSTOM_ORDER_TABLE_OPTION, array() ); 189 | $extra_order_data = $order->get_meta_data(); 190 | 191 | if ( $extra_metakeys ) { 192 | // Loop over keys to find the values and add them to $order_data array. 193 | foreach ( $extra_order_data as $single_order_data ) { 194 | if ( ! in_array( $single_order_data->key, $extra_metakeys, true ) ) { 195 | continue; 196 | } 197 | 198 | $order_data[ $single_order_data->key ] = $single_order_data->value; 199 | } 200 | } 201 | 202 | // Convert dates to timestamps, if they exist. 203 | foreach ( array( 'date_completed', 'date_paid' ) as $date ) { 204 | if ( $order_data[ $date ] instanceof WC_DateTime ) { 205 | $order_data[ $date ] = $order_data[ $date ]->getTimestamp(); 206 | } 207 | } 208 | 209 | // Insert or update the database record. 210 | if ( ! wc_custom_order_table()->row_exists( $order_data['order_id'] ) ) { 211 | $inserted = $wpdb->insert( $table, $order_data ); // WPCS: DB call OK. 212 | 213 | if ( 1 !== $inserted ) { 214 | return; 215 | } 216 | 217 | /* 218 | * WooCommerce prior to 3.3 lacks some necessary filters to entirely move order details 219 | * into a custom database table. If the site is running WooCommerce < 3.3.0, store the 220 | * billing email and customer ID in the post meta table as well, for backwards-compatibility. 221 | */ 222 | if ( version_compare( WC()->version, '3.3.0', '<' ) ) { 223 | update_post_meta( $order->get_id(), '_billing_email', $order->get_billing_email() ); 224 | update_post_meta( $order->get_id(), '_customer_user', $order->get_customer_id() ); 225 | } 226 | } else { 227 | $changes = array_intersect_key( $order_data, $order->get_changes() ); 228 | 229 | /* 230 | * WC_Order::get_changes() will mark all address fields as changed if one has changed. 231 | * 232 | * If any of these fields are present, be sure we update the index column. 233 | */ 234 | if ( isset( $changes['billing_first_name'] ) ) { 235 | $changes['billing_index'] = $order_data['billing_index']; 236 | } 237 | 238 | if ( isset( $changes['shipping_first_name'] ) ) { 239 | $changes['shipping_index'] = $order_data['shipping_index']; 240 | } 241 | 242 | if ( ! empty( $changes ) ) { 243 | $wpdb->update( $table, $changes, array( 'order_id' => $order->get_id() ) ); // WPCS: DB call OK. 244 | } 245 | } 246 | 247 | $updated_props = array_keys( (array) $changes ); 248 | 249 | // If customer changed, update any downloadable permissions. 250 | $customer_props = array( 'customer_user', 'billing_email' ); 251 | 252 | if ( array_intersect( $customer_props, $updated_props ) ) { 253 | $data_store = WC_Data_Store::load( 'customer-download' ); 254 | $data_store->update_user_by_order_id( $order->get_id(), $order->get_customer_id(), $order->get_billing_email() ); 255 | } 256 | 257 | do_action( 'woocommerce_order_object_updated_props', $order, $updated_props ); 258 | } 259 | 260 | /** 261 | * Get amount already refunded. 262 | * 263 | * @global $wpdb 264 | * 265 | * @param WC_Order $order Order object. 266 | * 267 | * @return float The amount already refunded. 268 | */ 269 | public function get_total_refunded( $order ) { 270 | global $wpdb; 271 | 272 | $total = $wpdb->get_var( 273 | $wpdb->prepare( 274 | 'SELECT SUM(o.amount) FROM ' . esc_sql( wc_custom_order_table()->get_table_name() ) . " AS o 275 | INNER JOIN $wpdb->posts AS p ON ( p.post_type = 'shop_order_refund' AND p.post_parent = %d ) 276 | WHERE o.order_id = p.ID", 277 | $order->get_id() 278 | ) 279 | ); 280 | 281 | return floatval( $total ); 282 | } 283 | 284 | /** 285 | * Finds an order ID based on its order key. 286 | * 287 | * @param string $order_key The order key. 288 | * 289 | * @return int The ID of an order, or 0 if the order could not be found 290 | */ 291 | public function get_order_id_by_order_key( $order_key ) { 292 | global $wpdb; 293 | 294 | $table = wc_custom_order_table()->get_table_name(); 295 | 296 | return $wpdb->get_var( 297 | $wpdb->prepare( 298 | 'SELECT order_id FROM ' . esc_sql( $table ) . ' WHERE order_key = %s', 299 | $order_key 300 | ) 301 | ); 302 | } 303 | 304 | /** 305 | * Search order data for a term and return ids. 306 | * 307 | * @param string $term The search term. 308 | * 309 | * @return array An array of order IDs. 310 | */ 311 | public function search_orders( $term ) { 312 | global $wpdb; 313 | 314 | /** 315 | * Searches on meta data can be slow - this lets you choose what fields to search. 316 | * 3.0.0 added _billing_address and _shipping_address meta which contains all address data to make this faster. 317 | * This however won't work on older orders unless updated, so search a few others (expand this using the filter if needed). 318 | * 319 | * @var array 320 | */ 321 | $search_fields = array_map( 322 | 'wc_clean', 323 | apply_filters( 324 | 'woocommerce_shop_order_search_fields', 325 | array( 326 | '_billing_address_index', 327 | '_shipping_address_index', 328 | '_billing_last_name', 329 | '_billing_email', 330 | ) 331 | ) 332 | ); 333 | $term = wc_clean( $term ); 334 | $order_ids = array(); 335 | 336 | // Treat a numeric search term as an order ID. 337 | if ( is_numeric( $term ) ) { 338 | $order_ids[] = absint( $term ); 339 | } 340 | 341 | // Search for order meta fields. 342 | if ( ! empty( $search_fields ) ) { 343 | $mapping = WooCommerce_Custom_Orders_Table::get_postmeta_mapping(); 344 | $in_table = array_intersect( $search_fields, $mapping ); 345 | $meta_keys = array_diff( $search_fields, $in_table ); 346 | $table = wc_custom_order_table()->get_table_name(); 347 | 348 | // Find results based on search fields that map to table columns. 349 | if ( ! empty( $in_table ) ) { 350 | $columns = array_keys( array_intersect( $mapping, $in_table ) ); 351 | $where = array(); 352 | 353 | foreach ( $columns as $column ) { 354 | $where[] = "{$column} LIKE %s"; 355 | } 356 | 357 | // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare 358 | $order_ids = array_merge( 359 | $order_ids, 360 | $wpdb->get_col( 361 | $wpdb->prepare( 362 | 'SELECT DISTINCT order_id FROM ' . esc_sql( $table ) . ' WHERE ' . implode( ' OR ', $where ), 363 | array_fill( 0, count( $where ), '%' . $wpdb->esc_like( $term ) . '%' ) 364 | ) 365 | ) 366 | ); 367 | // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare 368 | } 369 | 370 | // For anything else, fall back to postmeta. 371 | if ( ! empty( $meta_keys ) ) { 372 | $order_ids = array_merge( 373 | $order_ids, 374 | $wpdb->get_col( 375 | $wpdb->prepare( 376 | " 377 | SELECT DISTINCT post_id FROM {$wpdb->postmeta} 378 | WHERE meta_value LIKE %s 379 | AND meta_key IN (" . implode( ',', array_fill( 0, count( $meta_keys ), '%s' ) ) . ')', 380 | array_merge( 381 | array( '%' . $wpdb->esc_like( $term ) . '%' ), 382 | $meta_keys 383 | ) 384 | ) 385 | ) 386 | ); 387 | } 388 | } 389 | 390 | // Search item names. 391 | $order_ids = array_merge( 392 | $order_ids, 393 | $wpdb->get_col( 394 | $wpdb->prepare( 395 | " 396 | SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items 397 | WHERE order_item_name LIKE %s", 398 | '%' . $wpdb->esc_like( $term ) . '%' 399 | ) 400 | ) 401 | ); 402 | 403 | // Reduce the array of order IDs to unique values. 404 | $order_ids = array_unique( $order_ids ); 405 | 406 | return apply_filters( 'woocommerce_shop_order_search_results', $order_ids, $term, $search_fields ); 407 | } 408 | 409 | /** 410 | * Populate custom table with data from postmeta, for migrations. 411 | * 412 | * @global $wpdb 413 | * 414 | * @param WC_Order $order The order object, passed by reference. 415 | * @param bool $delete Optional. Whether or not the post meta should be deleted. Default 416 | * is false. 417 | * 418 | * @return WP_Error|null A WP_Error object if there was a problem populating the order, or null 419 | * if there were no issues. 420 | */ 421 | public function populate_from_meta( &$order, $delete = false ) { 422 | global $wpdb; 423 | 424 | try { 425 | $table_data = $this->get_order_data_from_table( $order ); 426 | $order = WooCommerce_Custom_Orders_Table::populate_order_from_post_meta( $order ); 427 | 428 | $this->update_post_meta( $order ); 429 | } catch ( WC_Data_Exception $e ) { 430 | return new WP_Error( 'woocommerce-custom-order-table-migration', $e->getMessage() ); 431 | } 432 | 433 | if ( $wpdb->last_error ) { 434 | return new WP_Error( 'woocommerce-custom-order-table-migration', $wpdb->last_error ); 435 | } 436 | 437 | if ( true === $delete ) { 438 | foreach ( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() as $column => $meta_key ) { 439 | delete_post_meta( $order->get_id(), $meta_key ); 440 | } 441 | } 442 | } 443 | 444 | /** 445 | * Populate order postmeta from a custom table, for rolling back. 446 | * 447 | * @param WC_Order $order The order object, passed by reference. 448 | */ 449 | public function backfill_postmeta( &$order ) { 450 | $data = $this->get_order_data_from_table( $order ); 451 | 452 | if ( empty( $data ) ) { 453 | return; 454 | } 455 | 456 | if ( isset( $data['prices_include_tax'] ) ) { 457 | $data['prices_include_tax'] = wc_bool_to_string( $data['prices_include_tax'] ); 458 | } 459 | 460 | foreach ( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() as $column => $meta_key ) { 461 | if ( isset( $data[ $column ] ) ) { 462 | update_post_meta( $order->get_id(), $meta_key, $data[ $column ] ); 463 | } 464 | } 465 | } 466 | } 467 | -------------------------------------------------------------------------------- /includes/class-wc-order-refund-data-store-custom-table.php: -------------------------------------------------------------------------------- 1 | get_order_data_from_table( $refund ); 25 | 26 | if ( ! empty( $data ) ) { 27 | $refund->set_props( $data ); 28 | } else { 29 | /** 30 | * Removed automatic migration of data to custom table. 31 | * Instead, we try to fetch metadata normally from the table. 32 | */ 33 | $id = $refund->get_id(); 34 | $data = array(); 35 | 36 | // Loop over internal postmeta properties. 37 | foreach ( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() as $key => $value ) { 38 | $data[ $key ] = get_post_meta( $id, $value, true ); 39 | } 40 | 41 | // Get post for additional notes passed by the customer. 42 | $post = get_post( $id ); 43 | $data['customer_note'] = $post->post_excerpt; 44 | 45 | $refund->set_props( $data ); 46 | } 47 | } 48 | 49 | /** 50 | * Retrieve a single refund from the database. 51 | * 52 | * @global $wpdb 53 | * 54 | * @param WC_Order_Refund $refund The refund object. 55 | * 56 | * @return array The refund row, as an associative array. 57 | */ 58 | public function get_order_data_from_table( $refund ) { 59 | global $wpdb; 60 | 61 | $data = (array) $wpdb->get_row( 62 | $wpdb->prepare( 63 | 'SELECT * FROM ' . esc_sql( wc_custom_order_table()->get_table_name() ) . ' WHERE order_id = %d LIMIT 1', 64 | $refund->get_id() 65 | ), 66 | ARRAY_A 67 | ); // WPCS: DB call OK. 68 | 69 | // Expand anything that might need assistance. 70 | if ( isset( $data['prices_include_tax'] ) ) { 71 | $data['prices_include_tax'] = wc_string_to_bool( $data['prices_include_tax'] ); 72 | } 73 | 74 | return $data; 75 | } 76 | 77 | /** 78 | * Helper method that updates all the post meta for a refund based on it's settings in the 79 | * WC_Order_Refund class. 80 | * 81 | * @global $wpdb 82 | * 83 | * @param WC_Order_Refund $refund The refund to be updated. 84 | */ 85 | protected function update_post_meta( &$refund ) { 86 | global $wpdb; 87 | 88 | $table = wc_custom_order_table()->get_table_name(); 89 | $refund_data = array( 90 | 'order_id' => $refund->get_id(), 91 | 'discount_total' => $refund->get_discount_total( 'edit' ), 92 | 'discount_tax' => $refund->get_discount_tax( 'edit' ), 93 | 'shipping_total' => $refund->get_shipping_total( 'edit' ), 94 | 'shipping_tax' => $refund->get_shipping_tax( 'edit' ), 95 | 'cart_tax' => $refund->get_cart_tax( 'edit' ), 96 | 'total' => $refund->get_total( 'edit' ), 97 | 'version' => $refund->get_version( 'edit' ), 98 | 'currency' => $refund->get_currency( 'edit' ), 99 | 'prices_include_tax' => wc_bool_to_string( $refund->get_prices_include_tax( 'edit' ) ), 100 | 'amount' => $refund->get_amount( 'edit' ), 101 | 'reason' => $refund->get_reason( 'edit' ), 102 | 'refunded_by' => $refund->get_refunded_by( 'edit' ), 103 | ); 104 | 105 | // Add additional metakeys data. 106 | $extra_metakeys = get_option( WC_CUSTOM_ORDER_TABLE_OPTION, array() ); 107 | $extra_refund_data = $refund->get_meta_data(); 108 | 109 | if ( $extra_metakeys ) { 110 | // Loop over keys to find the values and add them to $refund_data array. 111 | foreach ( $extra_refund_data as $single_refund_data ) { 112 | if ( ! in_array( $single_refund_data->key, $extra_metakeys, true ) ) { 113 | continue; 114 | } 115 | 116 | $order_data[ $single_refund_data->key ] = $single_refund_data->value; 117 | } 118 | } 119 | 120 | // Insert or update the database record. 121 | if ( ! wc_custom_order_table()->row_exists( $refund_data['order_id'] ) ) { 122 | $inserted = $wpdb->insert( $table, $refund_data ); // WPCS: DB call OK. 123 | 124 | if ( 1 !== $inserted ) { 125 | return; 126 | } 127 | } else { 128 | $refund_data = array_intersect_key( $refund_data, $refund->get_changes() ); 129 | 130 | // There's nothing to update. 131 | if ( empty( $refund_data ) ) { 132 | return; 133 | } 134 | 135 | $wpdb->update( 136 | wc_custom_order_table()->get_table_name(), 137 | $refund_data, 138 | array( 'order_id' => (int) $refund->get_id() ) 139 | ); 140 | } 141 | 142 | do_action( 'woocommerce_order_refund_object_updated_props', $refund, $refund_data ); 143 | } 144 | 145 | /** 146 | * Populate the custom table row with post meta. 147 | * 148 | * @global $wpdb 149 | * 150 | * @param WC_Order_Refund $refund The refund object, passed by reference. 151 | * @param bool $delete Optional. Whether or not the post meta should be deleted. 152 | * Default is false. 153 | * 154 | * @return WP_Error|null A WP_Error object if there was a problem populating the refund, or null 155 | * if there were no issues. 156 | */ 157 | public function populate_from_meta( &$refund, $delete = false ) { 158 | global $wpdb; 159 | 160 | $refund = WooCommerce_Custom_Orders_Table::populate_order_from_post_meta( $refund ); 161 | 162 | $this->update_post_meta( $refund ); 163 | 164 | if ( $wpdb->last_error ) { 165 | return new WP_Error( 'woocommerce-custom-order-table-migration', $wpdb->last_error ); 166 | } 167 | 168 | if ( true === $delete ) { 169 | foreach ( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() as $column => $meta_key ) { 170 | delete_post_meta( $refund->get_id(), $meta_key ); 171 | } 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /includes/class-woocommerce-custom-orders-table-cli.php: -------------------------------------------------------------------------------- 1 | ] 43 | * : Set the duration of days, starting today, to skip archiving of orders. 44 | * For Ex: Setting this value to 45 will skip orders for the last 45 days from archiving. 45 | * --- 46 | * default: 30 47 | * --- 48 | 49 | * @global $wpdb 50 | * 51 | * @param array $args Positional arguments passed to the command. 52 | * @param array $assoc_args Associative arguments (options) passed to the command. 53 | * @return int The number of orders to be migrated. 54 | */ 55 | public function count( $args = array(), $assoc_args = array() ) { 56 | global $wpdb; 57 | 58 | $assoc_args = wp_parse_args( 59 | $assoc_args, 60 | array( 61 | 'duration' => 30, 62 | ) 63 | ); 64 | 65 | // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 66 | $order_count = $wpdb->get_var( $this->get_migration_query( 'COUNT(*)', 0, 0, $assoc_args['duration'] ) ); 67 | 68 | WP_CLI::log( 69 | sprintf( 70 | /* Translators: %1$d is the number of orders to be migrated. */ 71 | _n( 'There is %1$d order to be migrated.', 'There are %1$d orders to be migrated.', $order_count, 'woocommerce-custom-orders-table' ), 72 | $order_count 73 | ) 74 | ); 75 | 76 | return (int) $order_count; 77 | } 78 | 79 | /** 80 | * List and save all additional postmeta keys for `shop_order` post type. 81 | * 82 | * ## EXAMPLES 83 | * wp wc orders-table optimize 84 | * 85 | * @global $wpdb 86 | * 87 | * @return WP_CLI 88 | */ 89 | public function optimize() { 90 | global $wpdb; 91 | 92 | $added = 0; 93 | $order_types = wc_get_order_types( 'reports' ); 94 | $meta_keys = $wpdb->get_col( 95 | $wpdb->prepare( 96 | // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery 97 | 'SELECT DISTINCT meta_key FROM wp_postmeta as pm, wp_posts as p WHERE meta_key NOT LIKE "_oembed%" AND pm.post_id = p.ID AND p.post_type IN (' . implode( ', ', array_fill( 0, count( $order_types ), '%s' ) ) . ')', 98 | $order_types 99 | ) 100 | ); 101 | 102 | if ( empty( $meta_keys ) ) { 103 | return WP_CLI::error( 104 | esc_html__( 'No additional meta keys found.', 'woocommerce-custom-orders-table' ) 105 | ); 106 | } 107 | 108 | // Fetch stored metakeys. 109 | $metakeys_list = get_option( WC_CUSTOM_ORDER_TABLE_OPTION, array() ); 110 | 111 | foreach ( $meta_keys as $meta_key ) { 112 | if ( in_array( $meta_key, array_values( WooCommerce_Custom_Orders_Table::get_postmeta_mapping() ), true ) ) { 113 | continue; 114 | } 115 | 116 | // Check for key within blacklisted keys. 117 | if ( in_array( $meta_key, WooCommerce_Custom_Orders_Table::get_blacklisted_keys(), true ) ) { 118 | continue; 119 | } 120 | 121 | // Check if the key already exists from the DB. 122 | if ( in_array( $meta_key, $metakeys_list, true ) ) { 123 | continue; 124 | } 125 | 126 | array_push( $metakeys_list, $meta_key ); 127 | 128 | // Update counter. 129 | ++$added; 130 | } 131 | 132 | // Check if we have additional meta_keys. 133 | if ( ! $added > 0 ) { 134 | return WP_CLI::log( 135 | esc_html__( 'No additional meta keys were found.', 'woocommerce-custom-orders-table' ) 136 | ); 137 | } 138 | 139 | // Store additional meta_keys in database. 140 | update_option( WC_CUSTOM_ORDER_TABLE_OPTION, $metakeys_list ); 141 | 142 | return WP_CLI::success( 143 | esc_html__( 'Meta keys list has been updated in the database. Run `wp wc orders-table populate` command to create columns for the additional keys.', 'woocommerce-custom-orders-table' ) 144 | ); 145 | } 146 | 147 | /** 148 | * Create columns in the `woocommerce_orders` table for the additional meta keys. 149 | * 150 | * ## EXAMPLES 151 | * wp wc orders-table populate 152 | * 153 | * @global $wpdb 154 | * 155 | * @return WP_CLI 156 | */ 157 | public function populate() { 158 | global $wpdb; 159 | 160 | $cols_added = 0; 161 | $metakeys_list = get_option( WC_CUSTOM_ORDER_TABLE_OPTION ); 162 | 163 | if ( ! $metakeys_list ) { 164 | return WP_CLI::error( 165 | esc_html__( 'No additional meta keys found in the database.', 'woocommerce-custom-orders-table' ) 166 | ); 167 | } 168 | 169 | $order_table = wc_custom_order_table()->get_table_name(); 170 | 171 | // Loop over meta keys and check for existing column in the database. 172 | foreach ( $metakeys_list as $col_name ) { 173 | $column = $wpdb->get_col( 174 | $wpdb->prepare( 175 | // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared 176 | "SHOW COLUMNS FROM {$order_table} LIKE %s", 177 | $col_name 178 | ) 179 | ); 180 | 181 | // Column already exists. 182 | if ( $column ) { 183 | WP_CLI::log( 184 | sprintf( 185 | /* translators: %s: column name */ 186 | esc_html__( '`%s` column already exists in the database.', 'woocommerce-custom-orders-table' ), 187 | $col_name 188 | ) 189 | ); 190 | 191 | continue; 192 | } 193 | 194 | // Alter table to add column. 195 | $query = $wpdb->query( 196 | $wpdb->prepare( 197 | "ALTER TABLE {$order_table} ADD COLUMN `{$col_name}` text" 198 | ) 199 | ); 200 | 201 | if ( ! $query ) { 202 | WP_CLI::error( 203 | sprintf( 204 | /* translators: %s: column name */ 205 | esc_html__( 'There was an error while adding `%s` column to the table.', 'woocommerce-custom-orders-table' ), 206 | $col_name 207 | ) 208 | ); 209 | 210 | continue; 211 | } 212 | 213 | ++$cols_added; 214 | } 215 | 216 | // Add a message at the end. 217 | WP_CLI::success( 218 | sprintf( 219 | /* translators: %s: column name */ 220 | esc_html__( '%s columns added to the table.', 'woocommerce-custom-orders-table' ), 221 | $cols_added 222 | ) 223 | ); 224 | } 225 | 226 | /** 227 | * Migrate order data to the custom orders table. 228 | * 229 | * ## OPTIONS 230 | * 231 | * [--batch-size=] 232 | * : The number of orders to process in each batch. Passing a value of 0 will disable batching. 233 | * --- 234 | * default: 100 235 | * --- 236 | * 237 | * [--duration=] 238 | * : Set the duration of days, starting today, to skip archiving of orders. 239 | * For Ex: Setting this value to 45 will skip orders for the last 45 days from archiving. 240 | * --- 241 | * default: 30 242 | * --- 243 | * 244 | * [--save-post-meta] 245 | * : Preserve the original post meta after a successful migration. 246 | * Default behavior is to clean up post meta. 247 | * 248 | * ## EXAMPLES 249 | * 250 | * wp wc orders-table migrate --batch-size=100 --save-post-meta 251 | * 252 | * @global $wpdb 253 | * 254 | * @param array $args Positional arguments passed to the command. 255 | * @param array $assoc_args Associative arguments (options) passed to the command. 256 | */ 257 | public function migrate( $args = array(), $assoc_args = array() ) { 258 | global $wpdb; 259 | 260 | $assoc_args = wp_parse_args( 261 | $assoc_args, 262 | array( 263 | 'batch-size' => 100, 264 | 'duration' => 30, 265 | 'save-post-meta' => false, 266 | ) 267 | ); 268 | 269 | $order_count = $this->count( array(), array( 'duration' => $assoc_args['duration'] ) ); 270 | 271 | // Abort if there are no orders to migrate. 272 | if ( ! $order_count ) { 273 | return WP_CLI::warning( __( 'There are no orders to migrate, aborting.', 'woocommerce-custom-orders-table' ) ); 274 | } 275 | 276 | $order_table = wc_custom_order_table()->get_table_name(); 277 | $order_types = wc_get_order_types( 'reports' ); 278 | $progress = WP_CLI\Utils\make_progress_bar( 'Order Data Migration', $order_count ); 279 | $processed = 0; 280 | $batch_count = 1; 281 | 282 | // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 283 | $order_data = $wpdb->get_col( $this->get_migration_query( 'p.ID', $assoc_args['batch-size'], 0, $assoc_args['duration'] ) ); 284 | 285 | while ( ! empty( $order_data ) ) { 286 | 287 | // Debug message for batched migrations. 288 | if ( 0 !== $assoc_args['batch-size'] ) { 289 | WP_CLI::debug( 290 | sprintf( 291 | /* Translators: %1$d is the batch number, %2$d is the batch size. */ 292 | __( 'Beginning batch #%1$d (%2$d orders/batch).', 'woocommerce-custom-orders-table' ), 293 | $batch_count, 294 | $assoc_args['batch-size'] 295 | ) 296 | ); 297 | } 298 | 299 | // Iterate over each order in this batch. 300 | foreach ( $order_data as $order_id ) { 301 | $order = $this->get_order( $order_id ); 302 | 303 | // Either an error occurred or wc_get_order() could not find the order. 304 | if ( false === $order ) { 305 | $this->skipped_ids[] = $order_id; 306 | 307 | WP_CLI::warning( 308 | sprintf( 309 | /* Translators: %1$d is the order ID. */ 310 | __( 'Unable to retrieve order with ID %1$d, skipping', 'woocommerce-custom-orders-table' ), 311 | $order_id 312 | ) 313 | ); 314 | 315 | } else { 316 | $result = $order->get_data_store()->populate_from_meta( $order, ! $assoc_args['save-post-meta'] ); 317 | 318 | if ( is_wp_error( $result ) ) { 319 | $this->skipped_ids[] = $order_id; 320 | 321 | WP_CLI::warning( 322 | sprintf( 323 | /* Translators: %1$d is the order ID, %2$s is the error message. */ 324 | __( 'A database error occurred while migrating order %1$d, skipping: %2$s.', 'woocommerce-custom-orders-table' ), 325 | $order_id, 326 | $result->get_error_message() 327 | ) 328 | ); 329 | } else { 330 | $processed++; 331 | 332 | WP_CLI::debug( 333 | sprintf( 334 | /* Translators: %1$d is the migrated order ID. */ 335 | __( 'Order ID %1$d has been migrated.', 'woocommerce-custom-orders-table' ), 336 | $order_id 337 | ) 338 | ); 339 | } 340 | 341 | WP_CLI::debug( 342 | sprintf( 343 | /* Translators: %1$d is the migrated order ID. */ 344 | __( 'Order ID %1$d has been migrated.', 'woocommerce-custom-orders-table' ), 345 | $order_id 346 | ) 347 | ); 348 | } 349 | 350 | $progress->tick(); 351 | } 352 | 353 | $next_batch = array_filter( 354 | $wpdb->get_col( 355 | // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 356 | $this->get_migration_query( 'p.ID', $assoc_args['batch-size'], count( $this->skipped_ids ), $assoc_args['duration'] ) 357 | ) 358 | ); 359 | 360 | if ( $next_batch === $order_data ) { 361 | return WP_CLI::error( __( 'Infinite loop detected, aborting.', 'woocommerce-custom-orders-table' ) ); 362 | } else { 363 | $order_data = $next_batch; 364 | $batch_count++; 365 | } 366 | } 367 | 368 | $progress->finish(); 369 | 370 | // Issue a warning if no orders were migrated. 371 | if ( ! $processed ) { 372 | return WP_CLI::warning( __( 'No orders were migrated.', 'woocommerce-custom-orders-table' ) ); 373 | } 374 | 375 | if ( empty( $this->skipped_ids ) ) { 376 | return WP_CLI::success( 377 | sprintf( 378 | /* Translators: %1$d is the number of migrated orders. */ 379 | _n( '%1$d order was migrated.', '%1$d orders were migrated.', $processed, 'woocommerce-custom-orders-table' ), 380 | $processed 381 | ) 382 | ); 383 | } else { 384 | WP_CLI::warning( 385 | sprintf( 386 | /* Translators: %1$d is the number of orders migrated, %2$d is the number of skipped records. */ 387 | _n( '%1$d order was migrated, with %2$d skipped.', '%1$d orders were migrated, with %2$d skipped.', $processed, 'woocommerce-custom-orders-table' ), 388 | $processed, 389 | count( $this->skipped_ids ) 390 | ) 391 | ); 392 | } 393 | } 394 | 395 | /** 396 | * Copy order data into the postmeta table. 397 | * 398 | * Note that this could dramatically increase the size of your postmeta table, but is recommended 399 | * if you wish to stop using the custom orders table plugin. 400 | * 401 | * ## OPTIONS 402 | * 403 | * [--batch-size=] 404 | * : The number of orders to process in each batch. Passing a value of 0 will disable batching. 405 | * --- 406 | * default: 100 407 | * --- 408 | * 409 | * ## EXAMPLES 410 | * 411 | * # Copy all order data into the post meta table, 100 posts at a time. 412 | * wp wc orders-table backfill --batch-size=100 413 | * 414 | * @global $wpdb 415 | * 416 | * @param array $args Positional arguments passed to the command. 417 | * @param array $assoc_args Associative arguments (options) passed to the command. 418 | */ 419 | public function backfill( $args = array(), $assoc_args = array() ) { 420 | global $wpdb; 421 | 422 | $assoc_args = wp_parse_args( 423 | $assoc_args, 424 | array( 425 | 'batch-size' => 100, 426 | ) 427 | ); 428 | $order_table = wc_custom_order_table()->get_table_name(); 429 | $order_count = $wpdb->get_var( 'SELECT COUNT(order_id) FROM ' . esc_sql( $order_table ) ); // WPCS: DB call ok. 430 | 431 | // If batching has been disabled, set the batch size to the total order count (e.g. one batch). 432 | if ( 0 === $assoc_args['batch-size'] ) { 433 | $assoc_args['batch-size'] = $order_count; 434 | } 435 | 436 | $order_query = new QueryIterator( 'SELECT order_id FROM ' . esc_sql( $order_table ), $assoc_args['batch-size'] ); 437 | $progress = WP_CLI\Utils\make_progress_bar( 'Order Data Migration', $order_count ); 438 | $processed = 0; 439 | 440 | while ( $order_query->valid() ) { 441 | $order = $this->get_order( $order_query->current()->order_id ); 442 | 443 | if ( $order ) { 444 | WooCommerce_Custom_Orders_Table::migrate_to_post_meta( $order ); 445 | } 446 | 447 | $processed++; 448 | $progress->tick(); 449 | $order_query->next(); 450 | } 451 | 452 | $progress->finish(); 453 | 454 | // Issue a warning if no orders were migrated. 455 | if ( ! $processed ) { 456 | return WP_CLI::warning( __( 'No orders were migrated.', 'woocommerce-custom-orders-table' ) ); 457 | } 458 | 459 | WP_CLI::success( 460 | sprintf( 461 | /* Translators: %1$d is the number of migrated orders. */ 462 | _n( '%1$d order was migrated.', '%1$d orders were migrated.', $processed, 'woocommerce-custom-orders-table' ), 463 | $processed 464 | ) 465 | ); 466 | } 467 | 468 | /** 469 | * Callback function for the "woocommerce_caught_exception" action. 470 | * 471 | * @throws Exception Re-throw the previously-caught Exception. 472 | * 473 | * @param Exception $exception The Exception object. 474 | */ 475 | public static function handle_exceptions( $exception ) { 476 | throw $exception; 477 | } 478 | 479 | /** 480 | * Helper function for calling wc_get_order(), with error handling. 481 | * 482 | * @param int $order_id The order/refund ID. 483 | * 484 | * @return WC_Abstract_Order|bool Either the WC_Order/WC_Order_Refund object or false if the 485 | * order object couldn't be loaded. 486 | */ 487 | protected function get_order( $order_id ) { 488 | try { 489 | $order = wc_get_order( $order_id ); 490 | } catch ( Exception $e ) { 491 | $order = false; 492 | WP_CLI::warning( 493 | sprintf( 494 | /* Translators: %1$d is the order ID, %2$s is the exception message. */ 495 | __( 'Encountered an error retrieving order #%1$d: %2$s', 'woocommerce-custom-orders-table' ), 496 | $order_id, 497 | $e->getMessage() 498 | ) 499 | ); 500 | } 501 | 502 | return $order; 503 | } 504 | 505 | /** 506 | * Build a SQL query to get posts that require migration. 507 | * Orders not marked as "completed" or the ones less than 7 days old 508 | * are skipped from migration. 509 | * 510 | * @global $wpdb 511 | * 512 | * @param string $select The contents of the SELECT clause. 513 | * @param int $limit The maximum number of results to return, or '0' to not limit the number 514 | * of results. 515 | * @param int $offset The offset value. Default is 0. 516 | * @param int $duration Number of days to skip archiving. Default is 30. 517 | * 518 | * @return string The prepared SQL query. 519 | */ 520 | protected function get_migration_query( $select, $limit, $offset = 0, $duration = 30 ) { 521 | global $wpdb; 522 | 523 | $order_table = wc_custom_order_table()->get_table_name(); 524 | $order_types = wc_get_order_types( 'reports' ); 525 | $query = " 526 | SELECT {$select} 527 | FROM {$wpdb->posts} p 528 | LEFT JOIN {$order_table} o ON p.ID = o.order_id 529 | WHERE p.post_type IN (" . implode( ', ', array_fill( 0, count( $order_types ), '%s' ) ) . ') 530 | AND p.post_status IN ("wc-completed", "wc-processing", "wc-pending", "wc-on-hold", "wc-cancelled", "wc-refunded") 531 | AND p.post_modified <= DATE_SUB(SYSDATE(), INTERVAL ' . $duration . ' DAY) 532 | AND o.order_id IS NULL 533 | '; 534 | $parameters = $order_types; 535 | 536 | if ( $limit ) { 537 | $query .= 'LIMIT %d, %d'; 538 | $parameters[] = $offset; 539 | $parameters[] = $limit; 540 | } 541 | 542 | // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 543 | return $wpdb->prepare( $query, $parameters ); 544 | } 545 | } 546 | -------------------------------------------------------------------------------- /includes/class-woocommerce-custom-orders-table-filters.php: -------------------------------------------------------------------------------- 1 | $meta_query ) { 29 | 30 | // Flatten complex meta queries. 31 | if ( is_array( $meta_query ) && 1 === count( $meta_query ) && is_array( current( $meta_query ) ) ) { 32 | $meta_query = current( $meta_query ); 33 | } 34 | 35 | if ( isset( $meta_query['customer_emails'] ) ) { 36 | $query_args['wc_order_meta_query'][] = array_merge( 37 | $meta_query['customer_emails'], 38 | array( 39 | 'key' => 'billing_email', 40 | '_old_key' => $meta_query['customer_emails']['key'], 41 | ) 42 | ); 43 | } 44 | 45 | if ( isset( $meta_query['customer_ids'] ) ) { 46 | $query_args['wc_order_meta_query'][] = array_merge( 47 | $meta_query['customer_ids'], 48 | array( 49 | 'key' => 'customer_id', 50 | '_old_key' => $meta_query['customer_ids']['key'], 51 | ) 52 | ); 53 | } 54 | 55 | if ( isset( $meta_query['key'] ) ) { 56 | $column = array_search( $meta_query['key'], WooCommerce_Custom_Orders_Table::get_postmeta_mapping(), true ); 57 | 58 | if ( $column ) { 59 | $query_args['wc_order_meta_query'][] = array_merge( 60 | $meta_query, 61 | array( 62 | 'key' => $column, 63 | '_old_key' => $meta_query['key'], 64 | ) 65 | ); 66 | } else { 67 | // Let this meta query pass through unaltered. 68 | $query_args['_wc_has_meta_columns'] = true; 69 | } 70 | } 71 | } 72 | } 73 | 74 | // Add filters to address specific portions of the query. 75 | add_filter( 'posts_join', __CLASS__ . '::posts_join', 10, 2 ); 76 | add_filter( 'posts_where', __CLASS__ . '::meta_query_where', 100, 2 ); 77 | 78 | return $query_args; 79 | } 80 | 81 | /** 82 | * Filter the JOIN statement generated by WP_Query. 83 | * 84 | * @global $wpdb 85 | * 86 | * @param string $join The MySQL JOIN statement. 87 | * @param WP_Query $wp_query The WP_Query object, passed by reference. 88 | * 89 | * @return string The filtered JOIN statement. 90 | */ 91 | public static function posts_join( $join, $wp_query ) { 92 | global $wpdb; 93 | 94 | /* 95 | * Remove the now-unnecessary INNER JOIN with the post_meta table unless there's some post 96 | * meta that doesn't have a column in the custom table. 97 | * 98 | * @see WP_Meta_Query::get_sql_for_clause() 99 | */ 100 | if ( ! $wp_query->get( '_wc_has_meta_columns', false ) ) { 101 | // Match the post_meta table INNER JOIN, with or without an alias. 102 | $regex = "/\sINNER\sJOIN\s{$wpdb->postmeta}\s+(AS\s[^\s]+)?\s*ON\s\([^\)]+\)/i"; 103 | 104 | $join = preg_replace( $regex, '', $join ); 105 | } 106 | 107 | $table = esc_sql( wc_custom_order_table()->get_table_name() ); 108 | $join .= " LEFT JOIN {$table} ON ( {$wpdb->posts}.ID = {$table}.order_id ) "; 109 | 110 | // Don't necessarily apply this to subsequent posts_join filter callbacks. 111 | remove_filter( 'posts_join', __CLASS__ . '::posts_join', 10 ); 112 | 113 | return $join; 114 | } 115 | 116 | /** 117 | * Filter the "WHERE" portion of the MySQL query to look at the custom orders table instead of 118 | * post meta. 119 | * 120 | * @global $wpdb 121 | * 122 | * @param string $where The MySQL WHERE statement. 123 | * @param WP_Query $wp_query The WP_Query object, passed by reference. 124 | * 125 | * @return string The [potentially-] filtered WHERE statement. 126 | */ 127 | public static function meta_query_where( $where, $wp_query ) { 128 | global $wpdb; 129 | 130 | $meta_query = $wp_query->get( 'wc_order_meta_query' ); 131 | $table = esc_sql( wc_custom_order_table()->get_table_name() ); 132 | 133 | if ( empty( $meta_query ) ) { 134 | return $where; 135 | } 136 | 137 | foreach ( $meta_query as $query ) { 138 | $regex = $wpdb->prepare( '/\(\s?(\w+\.)?meta_key = %s AND (\w+\.)?meta_value /i', $query['_old_key'] ); 139 | $where = preg_replace( $regex, "( {$table}.{$query['key']} ", $where ); 140 | } 141 | 142 | // Ensure this doesn't affect all subsequent queries. 143 | remove_filter( 'posts_where', __CLASS__ . '::meta_query_where', 100 ); 144 | 145 | return $where; 146 | } 147 | 148 | /** 149 | * Filter the query constructed by WC_Admin_Report::get_order_report_data() so that report data 150 | * comes from the orders table, not postmeta. 151 | * 152 | * @global $wpdb 153 | * 154 | * @param array $query Components of the MySQL query. 155 | * 156 | * @return array The filtered query components. 157 | */ 158 | public static function filter_order_report_query( $query ) { 159 | global $wpdb; 160 | 161 | if ( empty( $query['join'] ) ) { 162 | return $query; 163 | } 164 | 165 | /* 166 | * Determine which JOIN statements are in play. 167 | * 168 | * This regular expression is designed to match queries in the following formats: 169 | * 170 | * - INNER JOIN $wpdb->postmeta AS meta_{key} ON (post.ID = meta_{key}.post_id AND meta_{key}.meta_key = {key}) 171 | * - INNER JOIN $wpdb->postmeta AS parent_meta_{key} ON (posts.post_parent = parent_meta_{key}.post_id) AND 172 | * (parent_meta_{key}.meta_key = {key}) 173 | */ 174 | $regex = '/(?:INNER|LEFT)\s+JOIN\s+' . preg_quote( $wpdb->postmeta, '/' ) . '\s+AS\s((?:parent_)?meta_([^\s]+))\s+ON\s+(\((?:[^)]+\)\s+AND\s+\()?[^\)]+\))/im'; 175 | 176 | // Return early if we have no matches. 177 | if ( ! preg_match_all( $regex, $query['join'], $matches ) ) { 178 | return $query; 179 | } 180 | 181 | /* 182 | * Build a list of replacements. 183 | * 184 | * These will take the form of 'meta_{key}.meta_value' => 'meta_{key}.{table_column}'. 185 | */ 186 | $mapping = WooCommerce_Custom_Orders_Table::get_postmeta_mapping(); 187 | $joins = array( 188 | 'post_id' => false, 189 | 'post_parent' => false, 190 | ); 191 | $table = esc_sql( wc_custom_order_table()->get_table_name() ); 192 | $replacements = array(); 193 | 194 | foreach ( $matches[0] as $key => $value ) { 195 | $table_plus_meta_value = $matches[1][ $key ] . '.meta_value'; 196 | $order_table_column = array_search( $matches[2][ $key ], $mapping, true ); 197 | 198 | // Don't replace the string if there isn't a table column mapped to this key. 199 | if ( false === $order_table_column ) { 200 | continue; 201 | } 202 | 203 | if ( false !== strpos( $matches[3][ $key ], 'posts.post_parent =' ) ) { 204 | $table_alias = 'order_parent_meta'; 205 | $joins['post_parent'] = true; 206 | } else { 207 | $table_alias = 'order_meta'; 208 | $joins['post_id'] = true; 209 | } 210 | 211 | $replacements[ $table_plus_meta_value ] = $table_alias . '.' . $order_table_column; 212 | $replacements[ $matches[0][ $key ] ] = ''; 213 | } 214 | 215 | // Update query fragments. 216 | $replacement_keys = array_keys( $replacements ); 217 | $replacement_vals = array_values( $replacements ); 218 | $query['select'] = str_replace( $replacement_keys, $replacement_vals, $query['select'] ); 219 | $query['where'] = str_replace( $replacement_keys, $replacement_vals, $query['where'] ); 220 | $query['join'] = str_replace( $replacement_keys, $replacement_vals, $query['join'] ); 221 | 222 | // If replacements have been made, join on the orders table. 223 | if ( $joins['post_id'] ) { 224 | $query['join'] .= " LEFT JOIN {$table} AS order_meta ON ( posts.ID = order_meta.order_id ) "; 225 | } 226 | 227 | if ( $joins['post_parent'] ) { 228 | $query['join'] .= " LEFT JOIN {$table} AS order_parent_meta ON ( posts.post_parent = order_parent_meta.order_id ) "; 229 | } 230 | 231 | return $query; 232 | } 233 | 234 | /** 235 | * When the add_order_indexes system status tool is run, populate missing address indexes in 236 | * the orders table. 237 | * 238 | * @global $wpdb 239 | * 240 | * @param array $tool Details about the tool that has been executed. 241 | */ 242 | public static function rest_populate_address_indexes( $tool ) { 243 | global $wpdb; 244 | 245 | if ( ! isset( $tool['id'] ) || 'add_order_indexes' !== $tool['id'] ) { 246 | return; 247 | } 248 | 249 | $table = wc_custom_order_table()->get_table_name(); 250 | 251 | $wpdb->query( 252 | 'UPDATE ' . esc_sql( $table ) . " 253 | SET billing_index = CONCAT_WS( ' ', billing_first_name, billing_last_name, billing_company, billing_company, billing_address_1, billing_address_2, billing_city, billing_state, billing_postcode, billing_country, billing_email, billing_phone ) 254 | WHERE billing_index IS NULL OR billing_index = ''" 255 | ); // WPCS: DB call ok. 256 | $wpdb->query( 257 | 'UPDATE ' . esc_sql( $table ) . " 258 | SET shipping_index = CONCAT_WS( ' ', shipping_first_name, shipping_last_name, shipping_company, shipping_company, shipping_address_1, shipping_address_2, shipping_city, shipping_state, shipping_postcode, shipping_country ) 259 | WHERE shipping_index IS NULL OR shipping_index = ''" 260 | ); // WPCS: DB call ok. 261 | } 262 | 263 | /** 264 | * Associate previous orders from an email address that matches that of a new customer. 265 | * 266 | * @param int $order_id The order ID. 267 | * @param WP_User $customer The customer object. 268 | */ 269 | public static function update_past_customer_order( $order_id, $customer ) { 270 | $order = wc_get_order( $order_id ); 271 | $order->set_customer_id( $customer->ID ); 272 | $order->save(); 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /includes/class-woocommerce-custom-orders-table-install.php: -------------------------------------------------------------------------------- 1 | get_table_name(); 54 | $collate = $wpdb->get_charset_collate(); 55 | $tables = " 56 | CREATE TABLE {$table} ( 57 | order_id BIGINT UNSIGNED NOT NULL COMMENT 'Order post ID', 58 | order_key varchar(100) DEFAULT NULL COMMENT 'Unique order key', 59 | customer_id BIGINT UNSIGNED NOT NULL COMMENT 'Customer ID. Will be 0 for guests.', 60 | billing_index varchar(255) DEFAULT NULL COMMENT 'Billing fields, concatenated for search', 61 | billing_first_name varchar(100) DEFAULT NULL COMMENT 'Billing first name', 62 | billing_last_name varchar(100) DEFAULT NULL COMMENT 'Billing last name', 63 | billing_company varchar(100) DEFAULT NULL COMMENT 'Billing company', 64 | billing_address_1 varchar(255) DEFAULT NULL COMMENT 'Billing street address', 65 | billing_address_2 varchar(200) DEFAULT NULL COMMENT 'Billing extended address', 66 | billing_city varchar(100) DEFAULT NULL COMMENT 'Billing city/locality', 67 | billing_state varchar(100) DEFAULT NULL COMMENT 'Billing state/province/locale', 68 | billing_postcode varchar(20) DEFAULT NULL COMMENT 'Billing postal code', 69 | billing_country char(2) DEFAULT NULL COMMENT 'Billing country (ISO 3166-1 Alpha-2)', 70 | billing_email varchar(200) NOT NULL COMMENT 'Billing email address', 71 | billing_phone varchar(200) DEFAULT NULL COMMENT 'Billing phone number', 72 | shipping_index varchar(255) DEFAULT NULL COMMENT 'Shipping fields, concatenated for search', 73 | shipping_first_name varchar(100) DEFAULT NULL COMMENT 'Shipping first name', 74 | shipping_last_name varchar(100) DEFAULT NULL COMMENT 'Shipping last name', 75 | shipping_company varchar(100) DEFAULT NULL COMMENT 'Shipping company', 76 | shipping_address_1 varchar(255) DEFAULT NULL COMMENT 'Shipping street address', 77 | shipping_address_2 varchar(200) DEFAULT NULL COMMENT 'Shipping extended address', 78 | shipping_city varchar(100) DEFAULT NULL COMMENT 'Shipping city/locality', 79 | shipping_state varchar(100) DEFAULT NULL COMMENT 'Shipping state/province/locale', 80 | shipping_postcode varchar(20) DEFAULT NULL COMMENT 'Shipping postal code', 81 | shipping_country char(2) DEFAULT NULL COMMENT 'Shipping country (ISO 3166-1 Alpha-2)', 82 | payment_method varchar(100) DEFAULT NULL COMMENT 'Payment method ID', 83 | payment_method_title varchar(100) DEFAULT NULL COMMENT 'Payment method title', 84 | discount_total varchar(100) NOT NULL DEFAULT 0 COMMENT 'Discount total', 85 | discount_tax varchar(100) NOT NULL DEFAULT 0 COMMENT 'Discount tax', 86 | shipping_total varchar(100) NOT NULL DEFAULT 0 COMMENT 'Shipping total', 87 | shipping_tax varchar(100) NOT NULL DEFAULT 0 COMMENT 'Shipping tax', 88 | cart_tax varchar(100) NOT NULL DEFAULT 0 COMMENT 'Cart tax', 89 | total varchar(100) NOT NULL DEFAULT 0 COMMENT 'Order total', 90 | version varchar(16) NOT NULL COMMENT 'Version of WooCommerce when the order was made', 91 | currency char(3) NOT NULL COMMENT 'Currency the order was created with', 92 | prices_include_tax varchar(3) NOT NULL COMMENT 'Did the prices include tax during checkout?', 93 | transaction_id varchar(200) NOT NULL COMMENT 'Unique transaction ID', 94 | customer_ip_address varchar(40) DEFAULT NULL COMMENT 'The customer\'s IP address', 95 | customer_user_agent text DEFAULT NULL COMMENT 'The customer\'s User-Agent string', 96 | created_via varchar(200) NOT NULL COMMENT 'Order creation method', 97 | date_completed varchar(20) DEFAULT NULL COMMENT 'Date the order was completed', 98 | date_paid varchar(20) DEFAULT NULL COMMENT 'Date the order was paid', 99 | cart_hash varchar(32) DEFAULT NULL COMMENT 'Hash of cart items to ensure orders are not modified', 100 | amount varchar(100) DEFAULT NULL COMMENT 'The refund amount', 101 | refunded_by BIGINT UNSIGNED DEFAULT NULL COMMENT 'The ID of the user who issued the refund', 102 | reason text DEFAULT NULL COMMENT 'The reason for the refund being issued', 103 | PRIMARY KEY (order_id), 104 | UNIQUE KEY `order_key` (`order_key`), 105 | KEY `customer_id` (`customer_id`), 106 | KEY `order_total` (`total`) 107 | ) $collate; 108 | "; 109 | 110 | // Apply the database migration. 111 | dbDelta( $tables ); 112 | 113 | // Store the table version in the options table. 114 | update_option( self::SCHEMA_VERSION_KEY, (int) self::$table_version, false ); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /includes/class-woocommerce-custom-orders-table.php: -------------------------------------------------------------------------------- 1 | table_name = $wpdb->prefix . 'woocommerce_orders'; 30 | 31 | // Use the plugin's custom data stores for customers and orders. 32 | add_filter( 'woocommerce_customer_data_store', __CLASS__ . '::customer_data_store' ); 33 | add_filter( 'woocommerce_order_data_store', __CLASS__ . '::order_data_store' ); 34 | add_filter( 'woocommerce_order-refund_data_store', __CLASS__ . '::order_refund_data_store' ); 35 | 36 | // Filter order report queries. 37 | add_filter( 'woocommerce_reports_get_order_report_query', 'WooCommerce_Custom_Orders_Table_Filters::filter_order_report_query' ); 38 | 39 | // Fill-in after re-indexing of billing/shipping addresses. 40 | add_action( 'woocommerce_rest_system_status_tool_executed', 'WooCommerce_Custom_Orders_Table_Filters::rest_populate_address_indexes' ); 41 | 42 | // When associating previous orders with a customer based on email, update the record. 43 | add_action( 'woocommerce_update_new_customer_past_order', 'WooCommerce_Custom_Orders_Table_Filters::update_past_customer_order', 10, 2 ); 44 | 45 | WC_Customer_Data_Store_Custom_Table::add_hooks(); 46 | 47 | // Register the table within WooCommerce. 48 | add_filter( 'woocommerce_install_get_tables', array( $this, 'register_table_name' ) ); 49 | 50 | // If we're in a WP-CLI context, load the WP-CLI command. 51 | if ( defined( 'WP_CLI' ) && WP_CLI ) { 52 | WP_CLI::add_command( 'wc orders-table', 'WooCommerce_Custom_Orders_Table_CLI' ); 53 | } 54 | } 55 | 56 | /** 57 | * Retrieve the WooCommerce orders table name. 58 | * 59 | * @return string The database table name. 60 | */ 61 | public function get_table_name() { 62 | /** 63 | * Filter the WooCommerce orders table name. 64 | * 65 | * @param string $table The WooCommerce orders table name. 66 | */ 67 | return apply_filters( 'wc_customer_order_table_name', $this->table_name ); 68 | } 69 | 70 | /** 71 | * Simple helper method to determine if a row already exists for the given order ID. 72 | * 73 | * @global $wpdb 74 | * 75 | * @param int $order_id The order ID. 76 | * 77 | * @return bool Whether or not a row already exists for this order ID. 78 | */ 79 | public function row_exists( $order_id ) { 80 | global $wpdb; 81 | 82 | return (bool) $wpdb->get_var( 83 | $wpdb->prepare( 84 | 'SELECT COUNT(order_id) FROM ' . esc_sql( $this->get_table_name() ) . ' WHERE order_id = %d', 85 | $order_id 86 | ) 87 | ); 88 | } 89 | 90 | /** 91 | * Retrieve the database table column => post_meta mapping. 92 | * 93 | * @return array An array of database columns and their corresponding post_meta keys. 94 | */ 95 | public static function get_postmeta_mapping() { 96 | $metakeys = array( 97 | 'order_key' => '_order_key', 98 | 'customer_id' => '_customer_user', 99 | 'payment_method' => '_payment_method', 100 | 'payment_method_title' => '_payment_method_title', 101 | 'transaction_id' => '_transaction_id', 102 | 'customer_ip_address' => '_customer_ip_address', 103 | 'customer_user_agent' => '_customer_user_agent', 104 | 'created_via' => '_created_via', 105 | 'date_completed' => '_date_completed', 106 | 'date_paid' => '_date_paid', 107 | 'cart_hash' => '_cart_hash', 108 | 109 | 'billing_index' => '_billing_address_index', 110 | 'billing_first_name' => '_billing_first_name', 111 | 'billing_last_name' => '_billing_last_name', 112 | 'billing_company' => '_billing_company', 113 | 'billing_address_1' => '_billing_address_1', 114 | 'billing_address_2' => '_billing_address_2', 115 | 'billing_city' => '_billing_city', 116 | 'billing_state' => '_billing_state', 117 | 'billing_postcode' => '_billing_postcode', 118 | 'billing_country' => '_billing_country', 119 | 'billing_email' => '_billing_email', 120 | 'billing_phone' => '_billing_phone', 121 | 122 | 'shipping_index' => '_shipping_address_index', 123 | 'shipping_first_name' => '_shipping_first_name', 124 | 'shipping_last_name' => '_shipping_last_name', 125 | 'shipping_company' => '_shipping_company', 126 | 'shipping_address_1' => '_shipping_address_1', 127 | 'shipping_address_2' => '_shipping_address_2', 128 | 'shipping_city' => '_shipping_city', 129 | 'shipping_state' => '_shipping_state', 130 | 'shipping_postcode' => '_shipping_postcode', 131 | 'shipping_country' => '_shipping_country', 132 | 133 | 'discount_total' => '_cart_discount', 134 | 'discount_tax' => '_cart_discount_tax', 135 | 'shipping_total' => '_order_shipping', 136 | 'shipping_tax' => '_order_shipping_tax', 137 | 'cart_tax' => '_order_tax', 138 | 'total' => '_order_total', 139 | 140 | 'version' => '_order_version', 141 | 'currency' => '_order_currency', 142 | 'prices_include_tax' => '_prices_include_tax', 143 | 144 | 'amount' => '_refund_amount', 145 | 'reason' => '_refund_reason', 146 | 'refunded_by' => '_refunded_by', 147 | ); 148 | 149 | // Get additional meta keys from the database. 150 | $extra_metakeys = get_option( WC_CUSTOM_ORDER_TABLE_OPTION, array() ); 151 | 152 | if ( ! $extra_metakeys ) { 153 | return $metakeys; 154 | } 155 | 156 | // Add additional meta keys for migration. 157 | foreach ( $extra_metakeys as $meta_key ) { 158 | if ( isset( $metakeys[ $meta_key ] ) ) { 159 | continue; 160 | } 161 | 162 | $metakeys[ $meta_key ] = $meta_key; 163 | } 164 | 165 | return $metakeys; 166 | } 167 | 168 | /** 169 | * Given a WC_Order object, fill its properties from post meta. 170 | * 171 | * @param WC_Order $order The WC_Order object to populate. 172 | * 173 | * @return WC_Order The populated WC_Order object. 174 | */ 175 | public static function populate_order_from_post_meta( $order ) { 176 | foreach ( self::get_postmeta_mapping() as $column => $meta_key ) { 177 | $meta = get_post_meta( $order->get_id(), $meta_key, true ); 178 | 179 | $table_data = $order->get_data_store()->get_order_data_from_table( $order ); 180 | if ( empty( $table_data->$column ) && ! empty( $meta ) ) { 181 | switch ( $column ) { 182 | case 'billing_index': 183 | case 'shipping_index': 184 | break; 185 | 186 | /* 187 | * Migration isn't the time to validate (and potentially throw exceptions); 188 | * if it was accepted into WooCommerce core, let it persist. 189 | * 190 | * If we're unable to set an email address due to $order->set_billing_email(), 191 | * try to circumvent the check by using reflection to call the protected 192 | * $order->set_address_prop() method. 193 | */ 194 | case 'billing_email': 195 | try { 196 | $order->set_billing_email( $meta ); 197 | } catch ( WC_Data_Exception $e ) { 198 | $method = new ReflectionMethod( $order, 'set_address_prop' ); 199 | $method->setAccessible( true ); 200 | $method->invoke( $order, 'email', 'billing', $meta ); 201 | } 202 | break; 203 | 204 | case 'prices_include_tax': 205 | $order->set_prices_include_tax( 'yes' === $meta ); 206 | break; 207 | 208 | default: 209 | if ( method_exists( $order, "set_{$column}" ) ) { 210 | $order->{"set_{$column}"}( $meta ); 211 | } 212 | break; 213 | } 214 | } 215 | } 216 | 217 | return $order; 218 | } 219 | 220 | /** 221 | * Register the table name within WooCommerce. 222 | * 223 | * @param array $tables An array of known WooCommerce tables. 224 | * 225 | * @return array The filtered $tables array. 226 | */ 227 | public function register_table_name( $tables ) { 228 | $table = $this->get_table_name(); 229 | 230 | if ( ! in_array( $table, $tables, true ) ) { 231 | $tables[] = $table; 232 | sort( $tables ); 233 | } 234 | 235 | return $tables; 236 | } 237 | 238 | /** 239 | * Restore an order's data in the post_meta table. 240 | * 241 | * @global $wpdb 242 | * 243 | * @param WC_Abstract_Order $order The order or refund object, passed by reference. 244 | * @param bool $delete Optional. Should the row in the custom table be deleted? 245 | * Default is false. 246 | */ 247 | public static function migrate_to_post_meta( &$order, $delete = false ) { 248 | global $wpdb; 249 | 250 | $data = $order->get_data_store()->get_order_data_from_table( $order ); 251 | 252 | if ( is_null( $data ) ) { 253 | return; 254 | } 255 | 256 | if ( isset( $data['prices_include_tax'] ) ) { 257 | $data['prices_include_tax'] = wc_bool_to_string( $data['prices_include_tax'] ); 258 | } 259 | 260 | foreach ( self::get_postmeta_mapping() as $column => $meta_key ) { 261 | if ( isset( $data[ $column ] ) ) { 262 | update_post_meta( $order->get_id(), $meta_key, $data[ $column ] ); 263 | } 264 | } 265 | 266 | // Remove the row from the custom table. 267 | if ( true === $delete ) { 268 | $wpdb->delete( 269 | wc_custom_order_table()->get_table_name(), 270 | array( 'order_id' => $order->get_id() ), 271 | array( '%d' ) 272 | ); 273 | } 274 | } 275 | 276 | /** 277 | * Retrieve the class name of the WooCommerce customer data store. 278 | * 279 | * @return string The data store class name. 280 | */ 281 | public static function customer_data_store() { 282 | return 'WC_Customer_Data_Store_Custom_Table'; 283 | } 284 | 285 | /** 286 | * Retrieve the class name of the WooCommerce order data store. 287 | * 288 | * @return string The data store class name. 289 | */ 290 | public static function order_data_store() { 291 | return 'WC_Order_Data_Store_Custom_Table'; 292 | } 293 | 294 | /** 295 | * Retrieve the class name of the WooCommerce order refund data store. 296 | * 297 | * @return string The data store class name. 298 | */ 299 | public static function order_refund_data_store() { 300 | return 'WC_Order_Refund_Data_Store_Custom_Table'; 301 | } 302 | 303 | /** 304 | * List of keys which are not required to be migrated. 305 | * 306 | * @return array List of blacklisted keys. 307 | */ 308 | public static function get_blacklisted_keys() { 309 | return array( 310 | '_edit_lock', 311 | '_edit_last', 312 | ); 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | Contributors: liquidweb, mindsize, stevegrunwell 2 | Tags: woocommerce, performance 3 | Requires at least: 4.9 4 | Tested up to: 5.0.1 5 | Requires PHP: 5.2.4 6 | Stable tag: 1.0.0 7 | License: GNU General Public License v2.0 8 | License URI: http://www.gnu.org/licenses/gpl-2.0.html 9 | 10 | Store WooCommerce order data in a custom table for improved performance. 11 | 12 | == Description == 13 | 14 | This plugin improves WooCommerce performance by introducing a custom table to hold all of the most common order information in a single, properly-indexed location. 15 | 16 | ### Background 17 | 18 | [WooCommerce 3.0 introduced the notion of CRUD (Create, Read, Update, and Delete) interfaces](https://woocommerce.wordpress.com/2016/10/27/the-new-crud-classes-in-woocommerce-2-7/) in a move to unify the way WooCommerce data is stored and retrieved. However, orders are still stored as custom post types within WordPress, with each piece of order information (billing address, shipping address, taxes, totals, and more) being stored in post meta. In fact, WooCommerce will typically create over **40 separate post meta entries** for every single order. If your store receives even 10 orders a day, that means 400 new rows in the table every single day! The larger the post meta table grows, the longer queries will take to execute, potentially slowing down queries (and thus page load times) for you and your visitors. WooCommerce Custom Orders Table uses the WooCommerce CRUD design to save order data into a single, flat table that's optimized for WooCommerce queries; one order means only one new row, with minimal performance impact. 19 | 20 | ### Requirements 21 | 22 | WooCommerce Custom Orders Table requires [WooCommerce 3.2.6 or newer](https://wordpress.org/plugins/woocommerce/). 23 | 24 | If you're looking to migrate existing order data, [you'll need to have the ability to run WP-CLI commands in your WooCommerce environment](http://wp-cli.org/). 25 | 26 | ### Contributing 27 | 28 | If you're interested in contributing to the development of the plugin or need to report an issue, please [see the contributing guidelines for the project on GitHub](https://github.com/liquidweb/woocommerce-custom-orders-table/blob/develop/CONTRIBUTING.md). 29 | 30 | == Installation == 31 | 32 | You may install the plugin as you would install any other plugin: either through the "WP Admin › Plugins › Add New" screen or uploading the zip archive into WordPress. 33 | 34 | After installing and activating the plugin, you'll need to migrate orders from post meta into the newly-created orders table via [WP-CLI](http://wp-cli.org/): 35 | 36 | $ wp wc orders-table migrate 37 | 38 | For additional information on available WP-CLI commands (including a built-in way to restore order post meta), [please see the plugin's GitHub README](https://github.com/liquidweb/woocommerce-custom-orders-table#migrating-order-data). 39 | 40 | == Frequently Asked Questions == 41 | 42 | = Will this harm existing order post meta? = 43 | 44 | Once activated, WooCommerce Custom Orders Table will register the custom table (`wp_woocommerce_orders`, by default) as the source for all order data. If a request is made to load data for an order that _doesn't_ exist in the custom table, the plugin will automatically migrate the corresponding post meta into a new table row. 45 | 46 | For the best performance, it's recommended that you [explicitly migrate order data via WP-CLI](https://github.com/liquidweb/woocommerce-custom-orders-table#migrating-order-data) rather than count on each order being migrated the first time it's loaded. 47 | 48 | = Can I restore my order post meta if I don't like the custom table? = 49 | 50 | If you decide that WooCommerce Custom Orders Table isn't right for you, [the plugin includes a handy `backfill` WP-CLI command](https://github.com/liquidweb/woocommerce-custom-orders-table#copying-data-from-the-orders-table-into-post-meta), which puts all of the data back into post meta. 51 | 52 | Be forewarned, running `backfill` on a store with many orders will cause the post meta table to balloon quickly, so this is not recommended during peak traffic times. 53 | 54 | = Will using a custom table for order data break anything else within WooCommerce? = 55 | 56 | During development, we've been _extremely_ careful not to break existing WooCommerce functionality; our mantra on the project has been "if it works in stock WooCommerce, it had better work with our plugin active." 57 | 58 | To this end, [the plugin test suite](https://travis-ci.org/liquidweb/woocommerce-custom-orders-table) actually bootstraps WooCommerce's core test suite, ensuring that every test within WooCommerce passes when the Custom Orders Table plugin is active. [You can read more about confidently testing WooCommerce plugins in this blog post](https://stevegrunwell.com/blog/writing-woocommerce-extensions/). 59 | 60 | == Changelog == 61 | 62 | For a complete list of all changes, please [see the plugin changelog on GitHub](https://github.com/liquidweb/woocommerce-custom-orders-table/blob/develop/CHANGELOG.md). 63 | 64 | = 1.0.0 = 65 | * Initial public release of the plugin. 66 | -------------------------------------------------------------------------------- /woocommerce-custom-orders-table.php: -------------------------------------------------------------------------------- 1 | setup(); 84 | } 85 | 86 | return $wc_custom_order_table; 87 | } 88 | 89 | add_action( 'woocommerce_init', 'wc_custom_order_table' ); 90 | --------------------------------------------------------------------------------