Created
May 21, 2020 16:59
-
-
Save zenvisuals/608baf1f8097455f415f22cbd124e92c to your computer and use it in GitHub Desktop.
How to Setup Your First Wordpress Plugin?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Very Simple Plugin Settings</h1> | |
<form id="vsp_settings_form" method="POST" action="<?= esc_url(admin_url('admin-post.php')); ?>"> | |
<input type="hidden" name="action" value="vsp_update_option"> | |
<label for="vsp_text_value">Highly Complicated Text</label> | |
<input type="text" name="vsp_text_value" id="vsp_text_value"> | |
<?= submit_button("Submit") ?> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: My Very Simple Plugin | |
* Description: It does very simple things | |
* Author: Simple Man | |
*/ | |
if (!defined('WPINC')) { | |
die; | |
} | |
define('PLUGIN_TITLE', 'Very Simple Plugin'); | |
define('PLUGIN_TEXT_OPTION', 'vsp_plugin_text_option'); | |
function vsp_setup_admin_page() { | |
require_once plugin_dir_path(__FILE__) . 'views/admin-settings.php'; | |
} | |
function vsp_setup_admin_menu() { | |
add_menu_page(PLUGIN_TITLE, PLUGIN_TITLE, 'manage_options', 'vsp_admin_page', 'vsp_setup_admin_page'); | |
} | |
function vsp_handle_update_option() { | |
try { | |
$value = sanitize_text_field($_POST['vsp_text_value']); | |
update_option(PLUGIN_TEXT_OPTION, $value); | |
wp_safe_redirect( | |
add_query_arg(array( | |
'page' => 'vsp_admin_page', | |
'success' => true, | |
), admin_url('admin.php')) | |
); | |
} catch (Exception $e) { | |
wp_safe_redirect( | |
add_query_arg(array( | |
'page' => 'vsp_admin_page', | |
'success' => false | |
), admin_url('admin.php')) | |
); | |
} | |
} | |
function vsp_admin_notice() { | |
if (!isset($_GET['success'])) { | |
return; | |
} | |
if ($_GET['success'] === 'false') { | |
echo '<div class="notice notice-error"><p>Something went wrong</p></div>'; | |
return; | |
} | |
echo '<div class="notice notice-success"><p>Successfully updated settings!</p></div>'; | |
return; | |
} | |
function vsp_display_option_shortcode() { | |
return get_option(PLUGIN_TEXT_OPTION); | |
} | |
add_action('admin_menu', 'vsp_setup_admin_menu'); | |
add_action('admin_post_vsp_update_option', 'vsp_handle_update_option'); | |
add_action('admin_notices', 'vsp_admin_notice'); | |
add_shortcode('vsp_text', 'vsp_display_option_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment