Wordpress Plugin : Multiple values against same setting

Viewed 81

I am writing a plugin for category discounts. In Plugin Setting page, I have a Category and Discount_percentage fields. I am rending these as followings

function cat_slug_render(  ) { 

    $options = get_option( 'slug-configuration' );
    ?>
    <input type='text' size="50" name='slug-configuration[cat_slug]' value='<?php echo $options['cat_slug']; ?>'>
    <?php

}

and defining the option as

add_settings_field(
            'cat_slug', //id
            'category Slug',  //title
            'cat_slug_render', // callable 
            'slug-configuration', // page
            'configuration' //  section 
        );

everything else is fine. I can save the settings, can retrieve it, can update it and all. However, I can save just ONE value. My aim is to save multiple values using the same fields.

But I am confused here how can I do it. My ultimate goal is as follows

input cat slug
Input discount
Press save
this will insert a New record each time this process is done

any guidance or help is highly appreciated!

1 Answers

You can add to [cat_slug] as an array during save by using [] in the name attribute:

function cat_slug_render(  ) { 

    $options = get_option( 'slug-configuration', array() );
    ?>
    <input type='text' size="50" name='slug-configuration[cat_slug][]' value='<?php echo esc_html( $options['cat_slug'][0] ?? '' ); ?>'>
    <?php
}

However, you'll have to decide which value should be pre-loaded into the field if you are going to save multiple values. The first? The last? I've added [0] to the value, which should show the first, but if you want the most recent you could do something like:

function cat_slug_render(  ) { 

    $options = get_option( 'slug-configuration', array() );
    $last_key = array_key_last( $options );
    ?>
    <input type='text' size="50" name='slug-configuration[cat_slug][]' value='<?php echo esc_html( $options['cat_slug'][$last_key] ?? '' ); ?>'>
    <?php
}

Obviously make sure to update your sanitizer function if you try this, and note that value should be secured using esc_html() as well as your preferred method of isset (I've used ?? from PHP 7 or higher) if you want to prevent errors when nothing has been saved.

To display or use the values you've saved, you can use a foreach loop on the [cat_slug] array key:

$options = get_option( 'slug-configuration', array() )[cat_slug] ?? array();

foreach( $options as $option ) {

    // Do stuff.

}
Related