fbpx

Cách tạo các mục Menu con cho WordPress

Lưu ý hướng dẫn này hiện chỉ đang thiên về mặt giao diện và mang tới lý giải về cách các tinh chỉnh tại màn wp-admin

Nam Digital

Để tạo các mục Menu con cho WordPress, bạn có thể sử dụng

  • Hàm tạo menu con có sẵn của WordPress
  • ACF (Có giao diện đồ họa – Option page) hoặc sử dụng câu lệnh để khởi tạo Menu Option

Với ACF thì điều này khá đơn giản, làm lâu dài thì chúng ta lại lệ thuộc vào công cụ bên thứ 3, đặc biệt là khi bạn muốn viết các Plugins riêng rẽ và có thể chạy ổn áp ngay khi cài vào Web, chính vì vậy, Nam Digital khuyến khích bạn sử dụng hàm tạo menu con có sẵn của WordPress.

add_submenu_page(
	string $parent_slug,
	string $page_title,
	string $menu_title,
	string $capability,
	string $menu_slug,
	callable $function = ''
);

Những thành phần khai báo ở trên (dạng string) thì có thể tùy biến theo nhu cầu người dùng, quan trọng là hàm gọi lại (callable function),hãy cùng tìm hiểu theo ví dụ dưới đây

Ví dụ của hàm tạo Menu con có sẵn

Lets say we want to add a Sub-menu “WPOrg Options” to the “Tools” Top-level menu.

Plugins Developer Handbook

Ở ví dụ này, handbook muốn tạo một Submenu WpOrg Options nằm trong mục Tools (file tools.php sẽ quản lý phần đó). Chúng ta sẽ định nghĩa Submenu này đổ ra dữ liệu html gì, sau đó mới ghép chúng vào đúng vị trí

function wporg_options_page_html() {
	// check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		<form action="options.php" method="post">
			<?php
			// output security fields for the registered setting "wporg_options"
			settings_fields( 'wporg_options' );
			// output setting sections and their fields
			// (sections are registered for "wporg", each field is registered to a specific section)
			do_settings_sections( 'wporg' );
			// output save settings button
			submit_button( __( 'Save Settings', 'textdomain' ) );
			?>
		</form>
	</div>
	<?php
}

Đoạn check quyền người dùng, nếu người dùng không phải quyền manage option thì thoát hàm, tiếp đó ở đoạn wrap, để thay đổi thông số điều chỉnh, chúng ta dùng 1 form post sự thay đổi dữ liệu lên hàm option.php. Trong đó hàm bị thay đổi là wporg_options, hàm do_settings_sections mang tới sự thay đổi cho thành phần wporg

Đối với Form thì khi submit nút bấm, form sẽ gửi dữ liệu cần thay đổi wporg của fields wporg_options lên option.php, đó là theo ý hiểu của Nam

Tiếp đó, ta sẽ đăng ký hàm đó lên đúng vị trí, trong menu tên là Tools

function wporg_options_page()
{
	add_submenu_page(
		'tools.php',
		'WPOrg Options',
		'WPOrg Options',
		'manage_options',
		'wporg',
		'wporg_options_page_html'
	);
}
add_action('admin_menu', 'wporg_options_page');
Với 1 hàm callback hiển thị Form submit nội dung (dù chưa có gì) kèm hàm đăng ký khu vực hiển thị Settings, chúng ta đã lên được cấu trúc cơ bản cho một Submenu

Xây dựng hàm gọi lại với Submitting Form

Bản chất của việc xây dựng Option page là việc bạn Submit Form để kích hoạt 1 hook, từ đó cài hàm gọi lại theo ý muốn, Hook được truyền vào nên là Action Hook, đó là lý do chúng ta sẽ cải tiến hàm wporg_options_page như sau

function wporg_options_page() {
	$hookname = add_submenu_page(
		'tools.php',
		'WPOrg Options',
		'WPOrg Options',
		'manage_options',
		'wporg',
		'wporg_options_page_html'
	);

	add_action( 'load-' . $hookname, 'wporg_options_page_html_submit' );
}

add_action('admin_menu', 'wporg_options_page');

Như vậy chúng ta đã tạo 1 action hook mới với tên là load-hookname, lúc này chỉ cần đẩy logic mong muốn vào hàm gọi lại đó. Hàm này sẽ chạy ngay khi ta access vào bảng submit form

Lưu ý là hàm wporgs settings chưa được đăng ký nên việc submit sẽ không có tác dụng

wporg options

Đối với Menu cấp Top menu

Đây là cấp cao nhất trong cách tạo các phần tinh chỉnh, nên ta cần dùng hàm khác

add_menu_page(
    string $page_title,
    string $menu_title,
    string $capability,
    string $menu_slug,
    callable $function = '',
    string $icon_url = '',
    int $position = null
);

Dưới đây là ví dụ tương tự như Sub-menu ở phía trên

function wporg_options_page_html() {
    ?>
    <div class="wrap">
      <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
      <form action="options.php" method="post">
        <?php
        // output security fields for the registered setting "wporg_options"
        settings_fields( 'wporg_options' );
        // output setting sections and their fields
        // (sections are registered for "wporg", each field is registered to a specific section)
        do_settings_sections( 'wporg' );
        // output save settings button
        submit_button( __( 'Save Settings', 'textdomain' ) );
        ?>
      </form>
    </div>
    <?php
}

Đoạn này mình đã lý giải rồi nên sẽ không nhắc lại nữa, bước 2 là đẩy phần hàm này vào hàm đăng ký Top menu tương ứng

add_action( 'admin_menu', 'wporg_options_page' );
function wporg_options_page() {
    add_menu_page(
        'WPOrg',
        'WPOrg Options',
        'manage_options',
        'wporg',
        'wporg_options_page_html',
        plugin_dir_url(__FILE__) . 'images/icon_wporg.png',
        20
    );
}

Nếu bạn làm themes thì phần này thay vì dùng plugin_dir_url, ta sẽ dùng đoạn get_stylesheet_directory_uri()

Khi bạn viết 1 Plugin riêng biệt, bạn có thể trỏ hàm wporg_options_page_html sang một file php riêng

add_action( 'admin_menu', 'wporg_options_page' );
function wporg_options_page() {
    add_menu_page(
        'WPOrg',
        'WPOrg Options',
        'manage_options',
        plugin_dir_path(__FILE__) . 'admin/view.php',
        null,
        plugin_dir_url(__FILE__) . 'images/icon_wporg.png',
        20
    );
}

Khi Submit Form

Khi Submit Form ở cấp này, ta xử lý tương tự đối với Submenu

Form action attributes

Form Action attributes là việc ta truyền các tham số phù hợp vào form để xử lý logic, bạn có thể tham khảo series Golang của Nam để tìm hiểu thêm

<form action="<?php menu_page_url( 'wporg' ) ?>" method="post">

Xử lý logic Form

add_action( 'admin_menu', 'wporg_options_page' );
function wporg_options_page() {
	$hookname = add_menu_page(
		'WPOrg',
		'WPOrg Options',
		'manage_options',
		'wporg',
		'wporg_options_page_html',
		plugin_dir_url(__FILE__) . 'images/icon_wporg.png',
		20
	);

	add_action( 'load-' . $hookname, 'wporg_options_page_submit' );
}

Đối với hook được tạo mới, bạn có thể truyền vào hàm wporg_options_page_submit thực hiện các tính năng sau:

  • Logic khi submit form ('POST' === $_SERVER['REQUEST_METHOD'])
  • Lọc và làm sạch dữ liệu

Ví dụ về 1 Settings page hoàn thiện

Dưới đây là một ví dụ hoàn thiện của Settings Pages, cấu trúc của nó sẽ bao gồm 3 phần

  • Settings API
  • Option API
  • Admin Menu: Tạo menu con và menu ở cấp top (ngay phần đầu bài)

Trong Handbook thì người viết đã tách riêng thành từng mục nhỏ, nhưng trong quá trình học của Nam Digital thì mình sẽ gộp vào, nhằm mục đích xây dựng cả tính năng Frontend lẫn Backend cho Settings này luôn

/**
 * @internal never define functions inside callbacks.
 * these functions could be run multiple times; this would result in a fatal error.
 */

/**
 * custom option and settings
 */
function wporg_settings_init() {
	// Register a new setting for "wporg" page.
	register_setting( 'wporg', 'wporg_options' );

	// Register a new section in the "wporg" page.
	add_settings_section(
		'wporg_section_developers',
		__( 'The Matrix has you.', 'wporg' ), 'wporg_section_developers_callback',
		'wporg'
	);

	// Register a new field in the "wporg_section_developers" section, inside the "wporg" page.
	add_settings_field(
		'wporg_field_pill', // As of WP 4.6 this value is used only internally.
		                        // Use $args' label_for to populate the id inside the callback.
			__( 'Pill', 'wporg' ),
		'wporg_field_pill_cb',
		'wporg',
		'wporg_section_developers',
		array(
			'label_for'         => 'wporg_field_pill',
			'class'             => 'wporg_row',
			'wporg_custom_data' => 'custom',
		)
	);
}

/**
 * Register our wporg_settings_init to the admin_init action hook.
 */
add_action( 'admin_init', 'wporg_settings_init' );


/**
 * Custom option and settings:
 *  - callback functions
 */


/**
 * Developers section callback function.
 *
 * @param array $args  The settings array, defining title, id, callback.
 */
function wporg_section_developers_callback( $args ) {
	?>
	<p id="<?php echo esc_attr( $args['id'] ); ?>"><?php esc_html_e( 'Follow the white rabbit.', 'wporg' ); ?></p>
	<?php
}

/**
 * Pill field callbakc function.
 *
 * WordPress has magic interaction with the following keys: label_for, class.
 * - the "label_for" key value is used for the "for" attribute of the <label>.
 * - the "class" key value is used for the "class" attribute of the <tr> containing the field.
 * Note: you can add custom key value pairs to be used inside your callbacks.
 *
 * @param array $args
 */
function wporg_field_pill_cb( $args ) {
	// Get the value of the setting we've registered with register_setting()
	$options = get_option( 'wporg_options' );
	?>
	<select
			id="<?php echo esc_attr( $args['label_for'] ); ?>"
			data-custom="<?php echo esc_attr( $args['wporg_custom_data'] ); ?>"
			name="wporg_options[<?php echo esc_attr( $args['label_for'] ); ?>]">
		<option value="red" <?php echo isset( $options[ $args['label_for'] ] ) ? ( selected( $options[ $args['label_for'] ], 'red', false ) ) : ( '' ); ?>>
			<?php esc_html_e( 'red pill', 'wporg' ); ?>
		</option>
 		<option value="blue" <?php echo isset( $options[ $args['label_for'] ] ) ? ( selected( $options[ $args['label_for'] ], 'blue', false ) ) : ( '' ); ?>>
			<?php esc_html_e( 'blue pill', 'wporg' ); ?>
		</option>
	</select>
	<p class="description">
		<?php esc_html_e( 'You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe.', 'wporg' ); ?>
	</p>
	<p class="description">
		<?php esc_html_e( 'You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes.', 'wporg' ); ?>
	</p>
	<?php
}

/**
 * Add the top level menu page.
 */
function wporg_options_page() {
	add_menu_page(
		'WPOrg',
		'WPOrg Options',
		'manage_options',
		'wporg',
		'wporg_options_page_html'
	);
}


/**
 * Register our wporg_options_page to the admin_menu action hook.
 */
add_action( 'admin_menu', 'wporg_options_page' );


/**
 * Top level menu callback function
 */
function wporg_options_page_html() {
	// check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// add error/update messages

	// check if the user have submitted the settings
	// WordPress will add the "settings-updated" $_GET parameter to the url
	if ( isset( $_GET['settings-updated'] ) ) {
		// add settings saved message with the class of "updated"
		add_settings_error( 'wporg_messages', 'wporg_message', __( 'Settings Saved', 'wporg' ), 'updated' );
	}

	// show error/update messages
	settings_errors( 'wporg_messages' );
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		<form action="options.php" method="post">
			<?php
			// output security fields for the registered setting "wporg"
			settings_fields( 'wporg' );
			// output setting sections and their fields
			// (sections are registered for "wporg", each field is registered to a specific section)
			do_settings_sections( 'wporg' );
			// output save settings button
			submit_button( 'Save Settings' );
			?>
		</form>
	</div>
	<?php
}

Đoạn đầu ta sẽ sử dụng Settings API để đăng ký một tinh chỉnh mới của WordPress

Option API

Option API cho phép ta lấy ra giá trị tinh chỉnh hoặc trực tiếp thay đổi giá trị tinh chỉnh, những dữ liệu này thường được lưu trong bảng {$wpdb->prefix}_options (Trong đó wpdb->prefix được định nghĩa tùy vào tinh chỉnh của bạn, thông thường bảng đó là wp_options)

Lấy giá trị đơn

// add a new option
add_option('wporg_custom_option', 'hello world!');
// get an option
$option = get_option('wporg_custom_option');

Lấy giá trị theo mảng

// array of options
$data_r = array('title' => 'hello world!', 1, false );
// add a new option
add_option('wporg_custom_option', $data_r);
// get an option
$options_r = get_option('wporg_custom_option');
// output the title
echo esc_html($options_r['title']);

Như vậy ở hàm ví dụ mục phía trên, ta sẽ xử lý option như sau. Áp dụng vào ví dụ thực tế, Nam nhận thấy có hàm đăng ký vị trí tinh chỉnh tại Menu trong WordPress

/**
 * Add the top level menu page.
 */
function wporg_options_page() {
	add_menu_page(
		'WPOrg',
		'WPOrg Options',
		'manage_options',
		'wporg',
		'wporg_options_page_html'
	);
}

Hàm này đưa tới 1 hàm options_page_html như là giá trị sẽ thể hiện khi ta bấm vào tinh chỉnh mới

function wporg_options_page_html() {
	// check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// add error/update messages

	// check if the user have submitted the settings
	// WordPress will add the "settings-updated" $_GET parameter to the url
	if ( isset( $_GET['settings-updated'] ) ) {
		// add settings saved message with the class of "updated"
		add_settings_error( 'wporg_messages', 'wporg_message', __( 'Settings Saved', 'wporg' ), 'updated' );
	}

	// show error/update messages
	settings_errors( 'wporg_messages' );
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
		<form action="options.php" method="post">
			<?php
			// output security fields for the registered setting "wporg"
			settings_fields( 'wporg' );
			// output setting sections and their fields
			// (sections are registered for "wporg", each field is registered to a specific section)
			do_settings_sections( 'wporg' );
			// output save settings button
			submit_button( 'Save Settings' );
			?>
		</form>
	</div>
	<?php
}

Ta nhận thấy đoạn submit form sẽ gửi tới hàm options.php một lệnh post, hiển thị settings_fields cho cụm wporg, thực hiện thay đổi cho cụm wporg.

Settings API

register_setting(    string $option_group,    string $option_name,    array $args = []);

Với hàm setings API này ta sẽ

  • Đăng ký 1 tinh chỉnh thuộc nhóm wporg
  • Tên các tinh chỉnh là wporg_options
add_settings_section(    string $id,    string $title,    callable $callback,    string $page,    array $args = []);

Tiếp đó ta sẽ set 1 section (list gồm nhiều settings)

add_settings_field(
		'wporg_field_pill', // As of WP 4.6 this value is used only internally.
		                        // Use $args' label_for to populate the id inside the callback.
			__( 'Pill', 'wporg' ),
		'wporg_field_pill_cb',
		'wporg',
		'wporg_section_developers',
		array(
			'label_for'         => 'wporg_field_pill',
			'class'             => 'wporg_row',
			'wporg_custom_data' => 'custom',
		)
	);

Settings này có tên là wporg_field_pill

  • Tên section là __( ‘Pill’, ‘wporg’ ), lý do chèn cụm __ ở đầu để sử dụng thư viện i18n trong việc dịch thuật (Thứ thực sự quan trọng khi làm với các dự án quốc tế)
  • Hàm gọi lại là hàm wporg_field_pill_cb
  • Nhóm tinh chỉnh là wporg, và khu vực tinh chỉnh là wporg_section_developers
  • mảng $args sẽ hiển thị tinh chỉnh cho cụm wporg_field_pill

Đối với hàm wporg_field_pill_cb nó có dạng như sau

function wporg_field_pill_cb( $args ) {
	// Get the value of the setting we've registered with register_setting()
	$options = get_option( 'wporg_options' );
	?>
	<select
			id="<?php echo esc_attr( $args['label_for'] ); ?>"
			data-custom="<?php echo esc_attr( $args['wporg_custom_data'] ); ?>"
			name="wporg_options[<?php echo esc_attr( $args['label_for'] ); ?>]">
		<option value="red" <?php echo isset( $options[ $args['label_for'] ] ) ? ( selected( $options[ $args['label_for'] ], 'red', false ) ) : ( '' ); ?>>
			<?php esc_html_e( 'red pill', 'wporg' ); ?>
		</option>
 		<option value="blue" <?php echo isset( $options[ $args['label_for'] ] ) ? ( selected( $options[ $args['label_for'] ], 'blue', false ) ) : ( '' ); ?>>
			<?php esc_html_e( 'blue pill', 'wporg' ); ?>
		</option>
	</select>
	<p class="description">
		<?php esc_html_e( 'You take the blue pill and the story ends. You wake in your bed and you believe whatever you want to believe.', 'wporg' ); ?>
	</p>
	<p class="description">
		<?php esc_html_e( 'You take the red pill and you stay in Wonderland and I show you how deep the rabbit-hole goes.', 'wporg' ); ?>
	</p>
	<?php
}

Hàm này trông phức tạp, nhưng bản chất là nó gọi ra 1 select box với giá trị là red và blue, cùng đoạn hướng dẫn dành cho mỗi giá trị, đồng thời nó cũng nhảy vào bảng wp_options để tìm ra giá trị wporg_options (Nếu trước đó đã thực hiện tinh chỉnh thì thay đổi đó sẽ lưu ở bảng này)

Array

Nam là 1 Growth Hacker, Developer đam mê với sự nghiệp phát triển web