為控制台的設定增加子選單

更新日期:2020-12-21

主要是利用 add_options_page 這個函式

add_action( 'admin_menu', 'add_my_option_menu');

function add_my_option_menu(){
	add_options_page(
		'page_title',
		'menu_title',
		'administrator',
		'my_edit_page_slug',
		'show_edit_html_page'
	);

	add_action( 'admin_init', function(){
		register_setting( 'my_options_group', 'my_options_name' );
	});
}
function show_edit_html_page() {
	
	$options = get_option('my_options_name');
?>
	<div class="wrap">
		<h1>標題</h1>
		
		<div class="card">
			<h2 class="title">區塊一</h2>
		</div>
			
		<form action="options.php" method="post">
			<?php settings_fields('my_options_group'); ?>
			<table class="form-table">
				<tbody>
					<tr>
						<th scope="row">文字內容</th>
						<td>
							 項目一 <input type="text" name="my_options_name[opt1]" value="<?php if(!empty($options['opt1'])) echo $options['opt1']; ?>">
						</td>
					</tr>
					<tr>
						<th scope="row">複選框</th>
						<td>
							<input type="checkbox" name="my_options_name[opt2]" value="2" <?php checked( $options['opt2'], "2" ); ?>> 項目二
							<input type="checkbox" name="my_options_name[opt3]" value="3" <?php checked( $options['opt3'], "3" ); ?>> 項目三
						</td>
					</tr>
					<tr>
						<th scope="row">選項按鈕</th>
						<td>
							<input type="radio" name="my_options_name[opt4]" value="4" <?php checked( $options['opt4'], "4" ); ?>> 項目四
							<input type="radio" name="my_options_name[opt4]" value="5" <?php checked( $options['opt4'], "5" ); ?>> 項目五
							<input type="radio" name="my_options_name[opt4]" value="6" <?php checked( $options['opt4'], "6" ); ?>> 項目六
						</td>
					</tr>					
					<tr>
						<th scope="row">下拉選單</th>
						<td>
							<select name="my_options_name[opt5]">
								<option> -- </option>
								<option value="7" <?php selected( $options['opt5'], "7" ); ?>>項目七</option>
								<option value="8" <?php selected( $options['opt5'], "8" ); ?>>項目八</option>
							</select>
						</td>
					</tr>

				</tbody>
			</table>
			<?php submit_button(); ?>
		</form>
	</div>

<?php
}

發佈留言