I’ve been to countless posts looking for the answer to this and have tried nearly every combination. So obviously, I’m missing a step so small that it’s likely unfathomable to the WordPress community.
My code writes the options to the database, but fails to display them back. The array is NOT set. Multiple options can be added and deleted.
Writes the data:
<?php
$mycontents = array('content' => $_POST['cont'], 'content2' => $_POST['cont2']);
update_option('slider_contents',$mycontents);
?>
Here are the database entries:
a:2:{s:7:"content";a:3:{i:0;s:19:"This is content 1-a";i:1;s:19:"This is content 2-a";i:2;s:19:"This is content 3-a";}s:8:"content2";a:3:{i:0;s:19:"This is content 1-b";i:1;s:19:"This is content 2-b";i:2;s:19:"This is content 3-b";}}
Trying to read and display the data:
<?php
$the_contents=get_option('slider_contents');
foreach ($the_contents as $content) {
$content1=stripslashes($content->content);
$content2=stripslashes($content->content2);
?>
<li><textarea name="cont[]" rows="3" style="width:70%;" ><?php echo $content1; ?></textarea><br><textarea name="cont2[]" rows="3" style="width:70%;" ><?php echo $content2; ?></textarea><br><input type="button" value="Delete this option" onClick="delete_field(this);" /><input type="button" value="Add new option" onClick="add_to_field(this);" /></li>
<?php } ?>
I’ve also tried…
<?php
$the_contents=get_option('slider_contents');
foreach ($the_contents as $content) {
$content1=stripslashes($content['content']);
$content2=stripslashes($content['content2']);
?>
The output of var_dump($the_contents);
is :
array(2) {
["content"]=> array(3) {
[0]=> string(19) "This is content 1-a"
[1]=> string(19) "This is content 2-a"
[2]=> string(19) "This is content 3-a"
}
["content2"]=> array(3) {
[0]=> string(19) "This is content 1-b"
[1]=> string(19) "This is content 2-b"
[2]=> string(19) "This is content 3-b"
}
}
Let’s look at your code. Your first code block is treating an array like an object so your second attempt is closer to accurate:
Assuming you did what I suggested and placed the
var_dump
where I have in that code block, then what is happening is this:foreach ($the_contents as $content) {
lets you loop through the array. At each iteration,$content
is itself an array that looks like:So when you try to access
$content['content']
you are trying to access a key that doesn’t exist– you’ve already looped “past” that. You can demonstrate this for yourself by running:What you need to be doing is looping over that
$contents
array and taking each piece individually.