Skip to content

Instantly share code, notes, and snippets.

@verygoodplugins
Created December 8, 2022 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save verygoodplugins/a1ed088bf8db3bc9b7e46b468927413d to your computer and use it in GitHub Desktop.
Save verygoodplugins/a1ed088bf8db3bc9b7e46b468927413d to your computer and use it in GitHub Desktop.
WordPress plugin created by ChatGPT (https://i.wpfusion.com/8p22pV)
<?php
// Define a class for our plugin
class MyPlugin {
// Define a static property to hold the single instance of the class
private static $instance;
// Define a private constructor to prevent the class from being instantiated directly
private function __construct() {
// Add the admin settings page to the WordPress admin menu
add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
// Register a callback function to save the plugin settings
add_action( 'admin_post_my_plugin_save_settings', array( $this, 'save_settings' ) );
}
// Define a public static function to return the single instance of the class
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
// Define a function to add the admin settings page to the WordPress admin menu
public function add_admin_menu() {
add_options_page( 'My Plugin Settings', 'My Plugin', 'manage_options', 'my-plugin', array( $this, 'render_settings_page' ) );
}
// Define a function to render the admin settings page
public function render_settings_page() {
?>
<div class="wrap">
<h2>My Plugin Settings</h2>
<form action="<?php echo admin_url( 'admin-post.php' ); ?>" method="post">
<input type="hidden" name="action" value="my_plugin_save_settings">
<table class="form-table">
<tbody>
<tr>
<th scope="row">
<label for="my-plugin-setting">My Setting</label>
</th>
<td>
<input type="text" id="my-plugin-setting" name="my-plugin-setting" value="<?php echo get_option( 'my-plugin-setting' ); ?>">
</td>
</tr>
</tbody>
</table>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button button-primary" value="Save Settings">
</p>
</form>
</div>
<?php
}
// Define a function to save the plugin settings
public function save_settings() {
// Check that the current user has permission to save plugin settings
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Insufficient permissions' );
}
// Save the plugin setting
update_option( 'my-plugin-setting', $_POST['my-plugin-setting'] );
// Redirect the user back to the admin settings page
wp_redirect( admin_url( 'options-general.php?page=my-plugin' ) );
exit;
}
}
// Initialize the plugin by calling the get_instance() method of the singleton class
MyPlugin::get_instance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment