This seams to be basic -but I don’t get it.
If I query an option with get_option I get the string:
[{"title":"Brand Primary","value":"#2185D0","_id":"627a0637cf178d93e50be224cc07cd6e"},{"title":"Brand Secondary","value":"transparent","_id":"017280d9ec94a585c2de0bee8f49d8fb"},{"title":"Typo normal","value":"#383838","_id":"ff77119a11466c8d7a0efd612109fe6a"},{"title":"Typo on Brand Base","value":"#383838","_id":"8a3c1eebb8067b37fc47fc505f44b8b4"},{"value":"rgb(255, 255, 255)","title":"Typo on Brand Active","_id":"66fe7ced-3ef8-4dac-92c7-568d604c2931"}]
How can I change with php the value ‘#2185D0’ (Brand Primary) and ‘#383838’ (Brand base) without using this values by themselves (the are changing)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This is escaped JSON. Formatted nicely, it looks like this:
[
{
"title": "Brand Primary",
"value": "#2185D0",
"_id": "627a0637cf178d93e50be224cc07cd6e"
},
{
"title": "Brand Secondary",
"value": "transparent",
"_id": "017280d9ec94a585c2de0bee8f49d8fb"
},
{
"title": "Typo normal",
"value": "#383838",
"_id": "ff77119a11466c8d7a0efd612109fe6a"
},
{
"title": "Typo on Brand Base",
"value": "#383838",
"_id": "8a3c1eebb8067b37fc47fc505f44b8b4"
},
{
"value": "rgb(255, 255, 255)",
"title": "Typo on Brand Active",
"_id": "66fe7ced-3ef8-4dac-92c7-568d604c2931"
}
]
So you have an array of objects that contain titles and values.
To update a value inside it you need to:
- Get the value.
- Unescape it (remove the slashes).
- Parse the JSON into a PHP array.
- Loop over the PHP array to find the item with the title that you want to change.
- Change the value of that item.
- Re-encode the whole array as JSON.
- Save the value.
So something like this:
$color_items = get_option( 'cornerstone_color_items' );
$color_items = stripslashes( $color_items );
$color_items = json_decode( $color_items );
foreach ( $color_items as $color_item ) {
if ( 'Brand Primary' === $color_item->title ) {
$color_item->value = 'NEW VALUE HERE';
break;
}
}
$color_items = wp_json_encode( $color_items );
$color_items = addslashes( $color_items );
update_option( 'cornerstone_color_items', $color_items );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0