How to create a WordPress global options page?
Use the Settings API: add_options_page() for the page, register_setting() for the option, and add_settings_field() for the fields. This is the shortest complete example:
add_action( 'admin_menu', function () {
add_options_page( 'My Options', 'My Options', 'manage_options', 'my-options', 'my_options_page' );
} );
add_action( 'admin_init', function () {
register_setting( 'my_group', 'my_company', array( 'sanitize_callback' => 'sanitize_text_field' ) );
add_settings_section( 'my_section', 'Company', '__return_false', 'my-options' );
add_settings_field( 'my_company', 'Company name', function () {
echo '<input type="text" name="my_company" value="' . esc_attr( get_option( 'my_company' ) ) . '">';
}, 'my-options', 'my_section' );
} );
function my_options_page() { ?>
<div class="wrap">
<h1>My Options</h1>
<form action="options.php" method="post">
<?php settings_fields( 'my_group' ); do_settings_sections( 'my-options' ); submit_button(); ?>
</form>
</div>
<?php }
Read the value anywhere with get_option( 'my_company' ). The sanitize callback cleans the value when it is saved:
register_setting( 'my_group', 'my_company', array( 'sanitize_callback' => 'sanitize_text_field' ) );
update_option( 'my_company', '<b>Acme</b> <script>x()</script>Ltd' );
echo get_option( 'my_company' );
Output
Acme Ltd
Full steps with a tested plugin: WordPress Plugin Settings Page.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |