Skip to content

Instantly share code, notes, and snippets.

@parsakafi
Last active November 23, 2021 23:07
Show Gist options
  • Save parsakafi/473c88328eb83a7c425ec3e4d7dcfef2 to your computer and use it in GitHub Desktop.
Save parsakafi/473c88328eb83a7c425ec3e4d7dcfef2 to your computer and use it in GitHub Desktop.
Example WordPress Options Page
<?php
/*
Plugin Name: MyPlugin
Plugin URI: http://parsa.ws
Description: MyPlugin
Author: Parsa Kafi
Version: 1.0
Author URI: http://parsa.ws
*/
class MyPlugin
{
protected $option_key = 'MyPlugin-Key';
public function __construct() {
add_action( 'admin_menu', array( $this, 'menu' ) );
}
public function menu() {
add_options_page( 'My Options', 'My Plugin', 'manage_options', 'my-plugin', array( $this, 'settings_page' ) );
}
public function settings_page() {
$update_message = '';
if ( isset( $_POST['MyPlugin'] ) && wp_verify_nonce( $_POST['MyPlugin'], 'settings_submit' ) ) {
unset( $_POST['MyPlugin'] );
update_option( $this->option_key, $_POST );
$update_message = '<div class="notice notice-success is-dismissible" ><p>' . __( 'Settings saved.' ) . '</p></div> ';
}
$option = $this->get_option();
?>
<div class="wrap">
<h1 class="wp-heading-inline">Settings</h1>
<?php echo $update_message; ?>
<form action="" method="post">
<?php wp_nonce_field( 'settings_submit', 'MyPlugin', false ); ?>
<table class="form-table">
<tr>
<th><label for="input-text-test">Name</label></th>
<td><input type="text" name="name" id="input-text-test"
value="<?php echo $option['name'] ?? '' ?>"
class="regular-text">
</td>
</tr>
<tr>
<th><label for="textarea-test">Text</label></th>
<td>
<textarea name="textarea-test" id="textarea-test" cols="30"
rows="5"><?php echo $option['textarea-test'] ?? '' ?></textarea>
</td>
</tr>
<tr>
<th><label for="checkbox-test">Checkbox</label></th>
<td>
<label><input type="checkbox" id="checkbox-test"
name="checkbox-test" <?php checked( $option['checkbox-test'] ?? 0, 1 ) ?>
value="1"> Active</label>
</td>
</tr>
<tr>
<th><label for="select-test">Select</label></th>
<td>
<select name="select-test" id="select-test">
<option value="-1">---</option>
<option value="yes" <?php selected( $option['select-test'] ?? '', 'yes' ) ?>>
Yes
</option>
<option value="no" <?php selected( $option['select-test'] ?? '', 'no' ) ?>>
No
</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="button button-primary"
value="<?php _e( 'Save' ) ?>"></td>
</tr>
</table>
</form>
</div>
<?php
}
public function get_option( $key = null, $default = null ) {
$option = get_option( $this->option_key );
if ( $key != null )
$option = $option[ $key ] ?? $default;
return $option;
}
}
new MyPlugin();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment