WordPress.org

Ready to get started?Download WordPress

Forums

Trying to use add_option to add an array, and get_option to access it (4 posts)

  1. richarduk
    Member
    Posted 3 years ago #

    Struggling a bit here.

    I'm trying to add an array using add_option.

    When I try to access the array using get_option I'm not getting the results I expect.

    Here's a simple demo of my code:

    $test = array(
    'a' => 'b',
    'c' => 'd',
    'e' => 'f',
    );
    
    add_option('something', "$test");  // I've done the  	register_setting    bit earlier on
    
    $result = get_option("$test"); 
    
    print_r ($result);  // The output is     Array
    
    echo '<br />';
    
    echo $result ['e'];  // The output is  f

    I'm not quite sure why print_r ($result) is only returning 'Array'.

    I want to access $result using foreach but obviously I'm not being allowed to since apparently there's an empty array. :-)

  2. Tim Priebe
    Member
    Posted 3 years ago #

    I'm 90% sure that when setting or retrieving the value, you need to remove the quote marks, since it's an array.

    In other words, change:

    add_option('something', "$test");

    to:

    add_option('something', $test);

    and change:

    $result = get_option("$test");

    to:

    $result = get_option($test);

    After that, you're right that you'll need to access the data with a foreach loop similar to this:

    foreach ($result AS $currentVal) {
      echo $currentVal . '<br />';
    }
  3. richarduk
    Member
    Posted 3 years ago #

    Genius!

    So simple!

    Eugh!

    Thank you!

  4. Tim Priebe
    Member
    Posted 3 years ago #

    Not a problem, glad to help.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags