Skip to content

Instantly share code, notes, and snippets.

@oddjar
Last active December 6, 2022 19:19
Show Gist options
  • Save oddjar/6ff308cd9e634ccef225046b51565aa1 to your computer and use it in GitHub Desktop.
Save oddjar/6ff308cd9e634ccef225046b51565aa1 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: My Great Plugin
Description: A custom plugin for WordPress.
Version: 1.0
Author: Your Name
*/
/*
This was generated by ChatGTP with the following prompt:
Create scaffolding for a WordPress plugin called "my great plugin". OOP. Include a custom menu item and a custom admin screen. On the admin screen, add a single text field called "api_key" for saving an option called "api_key". Validate the field for letters only before saving.
*/
// Register a custom admin screen for the plugin
add_action( 'admin_menu', 'my_great_plugin_admin_menu' );
function my_great_plugin_admin_menu() {
add_menu_page(
'My Great Plugin', // Page title
'My Great Plugin', // Menu title
'manage_options', // Capability
'my-great-plugin', // Menu slug
'my_great_plugin_admin_screen', // Callback function
'dashicons-admin-plugins', // Icon
99 // Position
);
}
// Display the custom admin screen for the plugin
function my_great_plugin_admin_screen() {
echo '<h1>My Great Plugin</h1>';
echo '<p>This is the custom admin screen for the plugin.</p>';
// Check if the form has been submitted
if ( isset( $_POST['my_great_plugin_api_key_form'] ) ) {
// Validate the API key field
if ( preg_match( '/^[a-zA-Z]+$/', $_POST['api_key'] ) ) {
// Save the API key
update_option( 'my_great_plugin_api_key', sanitize_text_field( $_POST['api_key'] ) );
echo '<div class="notice notice-success"><p>API key saved successfully.</p></div>';
} else {
echo '<div class="notice notice-error"><p>Invalid API key. Please enter only letters.</p></div>';
}
}
// Get the saved API key
$api_key = get_option( 'my_great_plugin_api_key', '' );
?>
<form method="post" action="">
<input type="hidden" name="my_great_plugin_api_key_form" value="1">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="api_key">API Key</label></th>
<td><input type="text" name="api_key" id="api_key" value="<?php echo esc_attr( $api_key ); ?>" class="regular-text"></td>
</tr>
</tbody>
</table>
<p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"></p>
</form>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment