Hi there,
I’ve encountered a strange issue regarding to the cornerstone pages and blocks. Because we’ve various staging systems running, every database related stuff gets synchronized with WP Migrate.
Because we’re using a Search and Replace Method to change the URL of everything from our Staging System to our Live version, everything get’s replaced, wich also includes the Cornerstone Templates.
Problem:
After Replacing everything, the page templates doesn’t work anymore. They show up in the dropdown, but you can’t choose them due to an error.
Error:
This happens because cornerstone is storing the template files as an array, wich means replacing the url doesn’t affect the specified length of the string as value.
For example:
s:29:"https://yourstagingdomain.com"
turns to
s:29:"https://yournewdomain.com"
but it should be
s:25:"https://yournewdomain.com"
Solution:
If it’s already to late and you have already replaced the old domain through the new one, you have to run the following sql statement first on your production system to roll back the domain to the staging one (Otherwise the array will be broken):
UPDATE your_tablename SET meta_value = replace(meta_value, 'https://yournewdomain.com', 'https://yourstagingdomain.com') WHERE meta_key = 'cs_template_elements';
After this is done, you can use the following code to replace all domains with iterating through the array:
Also make sure to change the $replace
variable and the $by
variable to your values
To run the code, you can easily attach the following parameter to one of your sites: ?updatetemplates=1
/**
* Update the Cornerstone templates from the old to the new domain
*/
add_action('wp', function(){
if(!isset($_GET['updatetemplates']))
return;
$replace = 'https://yourstagingdomain.com';
$by = 'https://yournewdomain.com';
//Check if the psot exists
$check_args = array(
'post_type' => 'cs_user_templates',
'numberposts' => -1,
'meta_query' => array(
array(
'key' => 'cs_template_elements'
)
),
);
$templates = get_posts( $check_args );
if(empty($templates))
return;
foreach($templates as $template){
$meta = get_post_meta($template->ID, 'cs_template_elements', true);
$new_meta = jth_replace_cornerstone_template_values($meta, $replace, $by);
if(!empty($new_meta)){
update_post_meta($template->ID, 'cs_template_elements', $new_meta);
}
}
});
function jth_replace_cornerstone_template_values($array, $replace, $by){
foreach($array as $key => $stage){
if(is_array($stage)){
$array[$key] = call_user_func('jth_replace_cornerstone_template_values', $stage, $replace, $by);
} else {
$array[$key] = str_replace($replace, $by, $stage);
}
}
return $array;
}
If you have some questions, feel free to ask me here
Cheers
Jannis