samedi 23 janvier 2016

How to delete/update a WordPress plugin option

I am building a simple slider plugin and I am working on the options page that allows you to add new slides, use the media uploader and delete slides. However I cannot understand or find any helpful information on how you delete or update plugin options, or atleast where to run the delete_option() function.

When the user clicks the delete slide link I want the .s-image-row div related to that slide to dissapear and the option to be removed from the database when the page is saved.

Please help, thanks.

PHP - Options page (simplified)

function scratch_image_value( $option ) {

    $scratch_images = get_option( 'scratch_images' );

    //if the option is in the database and not an empty value
    if ( isset($scratch_images[$option]) && $scratch_images[$option] != ""  ) {
        echo $scratch_images[$option];
    //if the option does not exists in the database
    } else { 
        echo "http://localhost/my-site/wp-content/uploads/2015/09/03.jpg"; 
    }

}


<?php
$scratch_images = get_option('scratch_images');
$n = ( count($scratch_images) == 0 ) ? 1 : count($scratch_images);
?>

<input class="s-max-id" type="hidden" name="<?php echo $n; ?>" />

<div class="s-slides-wrapper">

    <?php for ($i = 1; $i <= $n; $i++) { ?>

        <div class="s-image-row">
            <img class="custom_media_image" src="<?php scratch_image_value($i); ?>" />
            <input class="custom_media_url" id="" type="text" name="scratch_images[<?php echo $i; ?>]" value="<?php scratch_image_value($i); ?>" >
            <a href="#" class="button scratch_media_upload">Upload</a>
            <a class="s-delete-slide" href="#">Delete slide</a>
        </div>

    <?php } ?>

</div> 

<a class="s-add-slide" href="#">Add slide</a>

<p class="submit">
    <input type="submit" class="button-primary" value="<?php _e('Save Options', 'scratch-slider'); ?>" />
</p>

jQuery (adding new slide)

jQuery( document ).ready(function(){

    counter = jQuery('.s-max-id').attr('name');
    counter = parseInt(counter);
    counter++;

    jQuery('.s-add-slide').click( function(event) {

        event.preventDefault();
        element = jQuery('.s-image-row').last().clone();

        new_counter = counter++;
        element.find('input').attr('name', 'scratch_images[' + new_counter + ']');
        jQuery('.s-slides-wrapper').append(element);

        return false;

    });

});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire