August 11, 2017 php Wordpress 0

Sometimes you might be in need of quickly storing and retrieveing data in WordPress for your plugin (in this example a simple delivery price is stored in wp_options table), and you don’t want to set up a separate database table and code to handle the database for this. The good news is that there is a very good and handy function already built into the core of WordPress. There are three functions that I’ll showcase below: add_option(), update_option(), and get_option(). Their role is self explanatory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
   
    // adds the option in the database
    // 5 is the price value
    add_option( 'woof_delivery', 5 );
    // if there is a post then update the option
    if(!empty($_POST['woof_delivery'])) update_option( 'woof_delivery', $_POST['woof_delivery'] );
    // get the option
    $woof_delivery = get_option('woof_delivery');
   
    echo '<h1>Delivery cost</h1>';
?>

<form target="_self" method="post">
   
    Delivery price: £<input style="border:none; background-color: #f1f1f1;" type="number" step="0.01" value="<?php echo $woof_delivery;?>" name="woof_delivery">
   
    <input type="submit" value="Update">


</form>
<br><br>