A week ago, we introduced the “clone as multiple” feature, which allows you to store cloneable values in multiple rows in the database. To make it works with your existing data, we make it optional and is turned off by default. However, some of you might want to convert the existing data to the new format, which allows you to perform a query based on custom field’s value. In this tutorial, I’ll show you a quick way to convert the existing custom field values to the new format and make “clone as multiple” feature works for you.
Assuming you have a cloneable custom field
start_date, which is created for a custom post type
'clone' => true, its value is a serialized string of an array like this:
['2019-05-01', '2019-04-30']). We need to convert that string back to an array of 2 elements and store them in 2 rows in the database.
And we need to loop through all events and process all of them. Here is the code:
The main code is in the
prefix_convert function. It does the following tasks:
- Query all events (a custom post type
- For each event, get the value of the cloneable field, which should be an array.
- Remove the custom field from the database.
- Loop through the value array of the field and insert a new row into the meta table.
To run this function, I created a simple trigger (the code below the
prefix_convert function). That code runs in the
init hook, it checks for a secret key in the URL (you should change it so you’re the only person who knows it) and perform the convert task.
Copy this file into your theme / plugin and just include it in your theme’s
To convert the old values, access your site via URL:
- Backup your database before running the code.
- If you have a staging website (or a copy of your website on your localhost), test the code on that first.
- After running the code, remove the
includestatement in you
functions.phpfile. This code should be run only once.
That’s it! Hope that helps you easier to use the new feature. If you have any question, please let me know in the comment.