SHOW:
|
|
- or go back to the newest paste.
| 1 | <?php | |
| 2 | /* | |
| 3 | Plugin Name: WordPress Options Example | |
| 4 | Description: WordPress options page example for a question asked in <a href="https://www.facebook.com/groups/1709897292614128">WordPress For Developers Group</a> | |
| 5 | Plugin URI: https://www.facebook.com/groups/1709897292614128 | |
| 6 | Author: Yehuda Hassine | |
| 7 | Author URI: https://www.facebook.com/groups/1709897292614128 | |
| 8 | Version: 1.0 | |
| 9 | License: GPL2 | |
| 10 | */ | |
| 11 | register_activation_hook( __FILE__, 'yh_activate' ); | |
| 12 | function yh_activate() {
| |
| 13 | add_option( 'yh_options_example', array( 'firstname' => '', 'lastname' => '' ) ); | |
| 14 | } | |
| 15 | ||
| 16 | register_deactivation_hook( __FILE__, 'yh_deactivate' ); | |
| 17 | function yh_deactivate() {
| |
| 18 | delete_option( 'yh_options_example' ); | |
| 19 | } | |
| 20 | ||
| 21 | add_action( 'admin_menu', 'yh_add_options_page' ); | |
| 22 | function yh_add_options_page() {
| |
| 23 | add_options_page( 'WordPress Options Example', 'WordPress Options Example', 'manage_options', 'yh', 'render_options_page' ); | |
| 24 | } | |
| 25 | ||
| 26 | function render_options_page() {
| |
| 27 | ?> | |
| 28 | <div class="wrap"> | |
| 29 | <?php | |
| 30 | $options = get_option( 'yh_options_example' ); | |
| 31 | ||
| 32 | if ( isset( $_POST['submit'] ) && isset( $_POST['data'] ) ) {
| |
| 33 | $data = array_map( 'sanitize_text_field', wp_unslash( $_POST['data'] ) ); | |
| 34 | ||
| 35 | update_option( 'yh_options_example', $data ); | |
| 36 | ?> | |
| 37 | <div id="setting-error-settings_updated" class="updated settings-error notice is-dismissible"> | |
| 38 | <p> | |
| 39 | <strong>Settings saved.</strong> | |
| 40 | </p> | |
| 41 | <button type="button" class="notice-dismiss"> | |
| 42 | <span class="screen-reader-text">Dismiss this notice.</span> | |
| 43 | </button> | |
| 44 | </div> | |
| 45 | <?php } ?> | |
| 46 | <form action="" method="post"> | |
| 47 | <label for="firstname"> | |
| 48 | <input type="text" id="firstname" name="data[firstname]" value="<?php echo show_option( $options['data']['firstname'] ); ?>" /> | |
| 49 | </label> | |
| 50 | <label for="lastname"> | |
| 51 | <input type="text" id="lastname" name="data[lastname]" value="<?php echo show_option( $options['data']['lastname'] ); ?>" /> | |
| 52 | </label> | |
| 53 | <button class="button button-primary" type="submit" name="submit">Submit</button> | |
| 54 | </form> | |
| 55 | </div> | |
| 56 | <?php | |
| 57 | } | |
| 58 | ||
| 59 | function show_option( $option ) {
| |
| 60 | if ( $option && ! empty( $option ) ) {
| |
| 61 | return esc_attr( $option ); | |
| 62 | } else {
| |
| 63 | return ''; | |
| 64 | } | |
| 65 | } |