Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am creating a plugin which has 5 textbox for options. What I need to do is to treat these 5 options as 1 item, and being able to add more items.

I've always worked with static hardcoded options for my wordpress plugins, so I am not sure how to do this, but I will try to do my best to explain myself.

I want to have a table similar to the posts table, then I want to be able to add/remove rows. Each row will be one "item" containing the 5 options.

Does someone knows a plugin that works similar to this so I can check it out? (if it also uses ajax that would be awesome)

My main problem is I am not sure how to save/retrieve the multiple rows because I always hardcoded my option names on the code.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I don't have a plugin to point you to off the top of my head, but my general suggestion is this: Store the relevant plugin settings in a single option, as an array. The crux of the reasoning here is that you're just adding items to a single array, which is auto-keyed, so you can add or subtract at will, without worrying about naming.

In practice, this means the following:

  • Build your markup so that the textboxes have the name attribute of a shared array, eg

    <input name="my_textboxes[]" />
    <input name="my_textboxes[]" />
    
  • When saving with AJAX, make sure you send the whole my_textboxes array as payload

  • Your callback for saving the settings can then be straightforward. Since the entire my_textboxes array gets sent on every save, you can just save the whole shebang to the options table, overwriting previous settings:

    $my_textboxes = $_POST['my_textboxes'];
    update_option( 'my_plugin_textboxes', $my_textboxes );
    

    Of course, you may want to loop over the value passed by $_POST['my_textboxes'] and do some sort of validation (check for duplicates, stuff like that).

  • When you're building the markup on page load, you'll just do a foreach loop:

    $my_textboxes = get_option( 'my_plugin_textboxes' );
    foreach( $my_textboxes as $key => $tb ) {
        echo '<input type="text" name="my_textboxes[]" value="' . esc_attr( $tb ) . '" />';
    }
    
share|improve this answer
    
I found the plugin wp-testimonials, which uses a separated database for the testimonials, I like that and I think im going to do that. Thanks a lot anyway. –  kyxrus Apr 17 '12 at 16:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.