15. Sử dụng WordPress Setting API toàn tập – P2

Như vậy sau khi kết thúc bài Sử dụng WordPress Settings API toàn tập – P1 thì trong bài hôm nay chúng ta sẽ tiếp tục tìm hiểu các phương thức còn lại của Setting API, nội dung trong bài sẽ hướng dẫn bạn tạo ra các phần tử form để nhập liệu, sau khi nhập liệu sẽ xử lý và đưa dữ liệu vào database. Ở bài Sử dụng WordPress Setting API toàn tập – P2 thì bạn sẽ hiểu thêm một số phương thức cũng như cách xử lý dữ liệu từ form và lưu vào database.

Kết thúc bài trước thì bạn đã biết cách tạo ra một phân đoạn nằm trong vùng nhập liệu của form, kế tiếp tôi & bạn sẽ tìm hiểu cách tạo ra các phần tử bẻn trong form, nếu đây đơn thuần là html thông thường thì nó đơn giản, nhưng tôi muốn nhấn mạnh với bạn rằng, chúng ta đang làm việc trên hệ thống của WordPress, mà muốn nhập liệu vào form rồi gửi dữ liệu sang page options.php xử lý để lưu vào database thì bạn cần phải tuân thủ một số quy tắc mà WordPress đặt ra. Do đó bạn cần phải sử dụng thêm các phương thức khác thuộc nhóm Setting API để đạt đúng chuẩn quy tắc nhập liệu của WordPress.

1/ Phương thức add_settings_field()

Phương thức này giúp bạn tạo ra các phần tử của form, nó bao gồm tất cả là 6 tham số , nhưng bạn chỉ cần quan tâm tới 5 tham số sau là đủ rồi.

Cú pháp:

1

add_settings_field($id, $title, $callback, $page, $section, $args);

Tham số:

· $id: Giá trị của thuộc tính id trong phần tử HTML.

· $title: Tiêu đề của phần tử.

· $callback: Hàm callback sử dụng tạo ra phần tử HTML

· $section : ID của section mà để gán phần tử form vào

· $page : Tên page hoặc menu slug của trang

Tôi sẽ tạo ra một phần tử texbox trong form dùng để nhập tiêu đề website.

1

2

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug);

Ở tham số đầu tiên là ID của phần tử form tôi truyền vào giá trị là lionel_new_title, ở tham số thứ hai là tên label hiển thị trong form, tham số thứ ba là phương thức dùng để xử lý khởi tạo textbox, tham số thứ tư là nơi hiển thị phần tử của form trên page nào.

Nội dung file backend.php:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

5

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

public function __construct(){

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug);

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting(){

}

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]" value=" />';

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Tội tạo mới phương thức new_title_input() để thể hiện đoạn code hiển thị textbox, vậy ở đây bạn chỉ cần chú ý phần khai báo name=”lionel_option[lionel_new_title], bạn cần phải kết hợp với tham số thứ hai ở phương thức register_setting(), và tham số đầu tiên của phương thức add_settings_field().

Do bạn cần phải xác định vị trí textbox hiển thị ở phân đoạn section nào , để tiện khai báo và tái sử dụng thì bạn tạo biến $mainSection = ‘lionel_main_section’ , biến này sẽ là tham số thứ năm được truyền vào trong phương thức đang làm việc.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

public function __construct(){

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

$mainSection = 'lionel_main_section';

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug, $mainSection);

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting(){

}

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]" value="" />';

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Sau khi đã tạo xong một texbox và hiển thị nó ở khu vực section được chỉ định, thì lúc này tôi sẽ tạo thêm một texbox nửa, và tôi có đoạn code xử lý như sau.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

public function __construct(){

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

$mainSection = 'lionel_main_section';

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

$extSection = 'lionel_ext_section';

add_settings_section('lionel_ext_section', 'Slogan', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug, $mainSection);

add_settings_field('lionel_new_slogan','

Slogan Title', array($this, 'new_slogan_input'), $this->_menuSlug, $extSection);

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting(){

}

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]" value="" />';

}

//=====================================================

// Phương thức new_slogan_input

//=====================================================

public function new_slogan_input(){

echo '<input type="text" name="lionel_option[lionel_new_slogan]" value="" />';

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Textbox mà tôi vừa tạo thêm có hiển thị là Slogan, nó nằm trong khu vực section mới có tên là Slogan. Bạn quay lại trình duyệt truy cập vào link http://localhost/wordpress/wp-admin/admin.php?page=lionel-my-setting để xem kết quả.

lionel-add-setting-field

Page Lionel Setting đã hiển thị ra 2 ô textbox và hiển thị ở hai vị trí phân đoạn section khác nhau. Khi bạn dùng phương thức add_settings_field() để khởi tạo ra các phần tử form thì hệ thống WordPress sẽ tự động bao bọc các phần tử đó trong cặp thẻ table.

Vấn đề lúc này, để lưu dữ liệu vào database thì bạn cần có một nút nhấn submit giống như ở các page khác, vậy thì tạo ra nó có khó không ? câu trả lời là khai báo phần hiển thị nút nhấn html ở file setting-page.php.

1

2

3

4

5

6

7

8

9

10

11

<div class="wrap">

<h2>My Setting page</h2>

<p>Đây là trang thiết lập cấu hình plugin Lionel Setting</p>

<form method="post" action="options.php" id="lionel_setting_form" enctype="multipart/form-data" >

<?php settings_fields('lionel_setting_options'); ?>

<?php do_settings_sections($this->_menuSlug); ?>

<p class="submit">

<input type="submit" name="submit" class="button button-primary" value="Save Changes">

</p>

</form>

</div>

Để tạo ra các nút nhấn có phần hiển thị giống với các page khác thì cách nhanh nhất là bạn F12 view đến nút nhấn đó rồi copy code html rồi paste vào sử dụng là được, do phần này khá đơn giản nên tôi sẽ không giải thích.

# Phương thức validate_setting():

Kế tiếp là phần xử lý dữ liệu để lưu vào database, lúc này bạn sẽ bắt đầu làm việc với phương thức validate_setting(), nó sẽ giúp bạn kiểm soát dữ liệu truyền vào trước khi bạn tiến hành lưu nó vào database.

Nếu bạn muốn lấy được dữ liệu thì cần có một tham số được truyền vào, tham số này chính là tham số chứa dữ liệu của [lionel_new_title], [lionel_new_slogan] ở textbox, bạn có thể truyền tham số vào phương thức với tên biến bất kì mà bạn muốn, tôi sẽ đặt là $data_input.

Để kiểm tra thì bạn cần in cái biến $data_input xem bạn nhận được dữ liệu gì sau khi nhập liệu trong form và nhấn nút Save changes.

1

2

3

4

5

6

7

8

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting($data_input){

echo '<pre>';

print_r($data_input);

echo '</pre>';

}

Tôi F5 trình duyệt và tiến hành nhập liệu bất cứ giá trị nào vào 2 ô texbox, sau đó nhấn nút để quá trình xử lý dữ liệu được khởi tạo và trình duyệt sẽ tự động F5 lại page cho bạn.

http://localhost/wordpress/wp-admin/admin.php?page=lionel-my-setting&settings-updated=true

Lúc này bạn sẽ thấy đường dẫn của bạn đã được nối thêm một giá trị là settings-updated=true, có nghĩa là đã cập nhật rồi, nhưng với cách này thì làm sao bạn thấy được dữ liệu gửi qua như thế nào. Do đó ngay phía dưới chỗ bạn in $data_input bạn sử dụng phương thức die() dừng xử lý code sau khi in dữ liệu ra và không lưu dữ liệu vào database.

lionel-validate_setting_api

Sau khi tôi nhập liệu xong và bấm nút lưu lại thì do tác dụng của phương thức die() nên bạn có thể thấy rằng nó gửi dữ liệu sang page options.php, dữ liệu hiện tại thuộc dạng array(mảng), phần tử đầu tiên chứa giá trị mà tôi nhập vào textbox thứ nhất, phần tử thứ hai chứa giá trị mà tôi nhập vào textbox thứ hai.

Vấn đề bây giờ bạn cần giải quyết là làm thế nào để lưu 2 giá trị này vào field lionel_option trong table wp_options ? Vì lúc nãy bạn đã nhấn nút để lưu dữ liệu nên nó đã tạo ra field lionel_option rồi, nhưng giá trị ở cột option_name là rỗng, vì dữ liệu bạn thêm vào vẫn chưa được xử lý để lưu vào.

Để lưu được dữ liệu thì khá là đơn giản, bạn chỉ cần return $data_input để nó nhận các kết quả trả về.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

public function __construct(){

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

$mainSection = 'lionel_main_section';

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

$extSection = 'lionel_ext_section';

add_settings_section('lionel_ext_section', 'Slogan', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug, $mainSection);

add_settings_field('lionel_new_slogan','

Slogan Title', array($this, 'new_slogan_input'), $this->_menuSlug, $extSection);

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting($data_input){

return $data_input;

}

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]" value="" />';

}

//=====================================================

// Phương thức new_slogan_input

//=====================================================

public function new_slogan_input(){

echo '<input type="text" name="lionel_option[lionel_new_slogan]" value="" />';

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Tôi quay lại trang lúc nãy bấm F5 và nhập liệu các giá trị vào, bấm nút save changes để kết thúc quá trình lưu dữ liệu vào database. Bạn kiểm tra bằng cách truy cập vào phpmyadmin tìm đến table wp_options xem kết quả có giống hình không nhen.

lionel-validate-setting-run

Tên của 2 field mà bạn khai báo ở trên đã được thêm vào database và nó ứng với giá trị mà bạn đã khai báo ở textbox. Vậy là bạn đã lưu được dữ liệu vào trong table wp_options, vậy giờ lấy giá trị của nó ra và hiển thị giá trị vào các ô textbox? Chắc hẳn bạn còn nhớ một phương thức thuộc nhóm Options API mà tôi đã trình bày ở các bài trước, nó cung cấp cho bạn một phương thức get_option(), giúp bạn lấy ra bất cứ giá trị của filed nào mà bạn đã chỉ định.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

private $_setting_option;

public function __construct(){

//=====================================================

// Biến toàn cục $_setting_option giúp bạn lấy ra các giá trị trong field lionel_option

//=====================================================

$this->_setting_option = get_option('lionel_option', array());

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

$mainSection = 'lionel_main_section';

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

$extSection = 'lionel_ext_section';

add_settings_section('lionel_ext_section', 'Slogan', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'new_title_input'), $this->_menuSlug, $mainSection);

add_settings_field('lionel_new_slogan','

Slogan Title', array($this, 'new_slogan_input'), $this->_menuSlug, $extSection);

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting($data_input){

return $data_input;

}

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]" value="" />';

}

//=====================================================

// Phương thức new_slogan_input

//=====================================================

public function new_slogan_input(){

echo '<input type="text" name="lionel_option[lionel_new_slogan]" value="" />';

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Bạn cần khởi tạo một biến toàn cục mới có tên là $_setting_option , biến toàn cục này sẽ hứng giá trị mà phương thức get_option() mang lại. Do bạn cần lấy ra các giá trị bên trong field lionel_option thì ở tham số đầu tiên bạn điền vào là lionel_option, tham số thứ hai có giá trị là mảng nên bạn cần khai báo cho nó sẵn một array rỗng.

Để lấy ra được giá trị thì ở hai phương thức new_title_input(), new_slogan_input(), phần value bạn sẽ bắt đầu sử dụng tới nó, ngay tại đó bạn khai báo như sau.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//=====================================================

// Phương thức new_title_input

//=====================================================

public function new_title_input(){

echo '<input type="text" name="lionel_option[lionel_new_title]"

value="'.$this->_setting_option['lionel_new_title'].'" />';

}

//=====================================================

// Phương thức new_slogan_input

//=====================================================

public function new_slogan_input(){

echo '<input type="text" name="lionel_option[lionel_new_slogan]"

value="'.$this->_setting_option['lionel_new_slogan'].'" />';

}

Thuộc tính $this->_setting_option[”] sẽ có một array chính là tham số đầu tiên của phương thức add_settings_field() , là tên id mà bạn đã khai báo.

Để kiểm tra , thì bạn cần phải F5 trình duyệt xem kết quả là 2 ô textbox có chứa giá trị mà bạn vừa nhập liệu vào database, có giữ lại giá trị mà bạn vừa truyền vào không.

lionel-get-option-api-field-lionel-option

Bạn có thể kiểm tra thêm bằng cách nhập giá trị mới xem textbox có giữ lại giá mới hay không. nếu textbox hiển thị dữ liệu mới thì bạn đã lưu dữ liệu vào database thành công rồi đấy.

4/ Phương thức add_settings_error()

Phương thức giúp bạn hiển thị các thông báo lỗi nhập liệu và khi cập nhật dữ liệu thành công, nó bao gồm 4 tham số.

Cú pháp:

1

add_settings_error($setting, $code, $message, $type);

Tham số:

· $setting: menu slug của trang.

· $code: Giá trị này sẽ kết hợp với chuỗi ‘setting-error-‘ để tạo ra thuộc tính id trong mã HTML.

· $message: Chuỗi thông báo lỗi

· $type: Kiểu thông báo, có 2 giá trị error và updated

Lúc này tôi sẽ kiểm tra hai textbox với điều kiện chỉ cho phép nhập liệu với giá trị tối đa là 20 ký tự, nếu vượt quá số ký tự thì sẽ hiển thị thông báo lỗi.

Để kiểm tra độ dài của ký tự thì bạn cần phải tạo ra một phương thức xử lý vấn đề này như sau.

1

2

3

4

5

6

7

8

9

10

11

12

13

//===============================================

//Kiem tra chieu chieu dai cua chuoi

//===============================================

private function stringMaxValidate($val, $max){

$flag = false;

$str = trim($val);

if(strlen($str) <= $max){

$flag = true;

}

return $flag;

}

Kế tiếp do giá trị thông báo lỗi trong WordPress có kiểu dữ liệu là array nên tôi sẽ khởi tạo biến $errors = array(), tức là mặc định giá trị sẽ là môt array rỗng.

Để tối ưu code hơn, tôi sẽ gộp 2 textbox kia thành 1 phương thức duy nhất và xác định chúng bằng tham số thứ 6 trong phương thức add_settings_field().

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

<?php

class LionelBackend {

private $_menuSlug = 'lionel-my-setting';

private $_setting_option;

public function __construct(){

//=====================================================

// Biến toàn cục $_setting_option giúp bạn lấy ra các giá trị trong field lionel_option

//=====================================================

$this->_setting_option = get_option('lionel_option', array());

//=====================================================

// Gọi Hook admin_menu xử lý và khởi tạo menu mới

//=====================================================

add_action('admin_menu', array($this, 'settingMenu'));

//=====================================================

// Gọi Hook admin_init để khởi tạo và xử lý phương thức

//=====================================================

add_action('admin_init', array($this, 'register_setting_and_field'));

}

//=====================================================

// Phương thức register_setting_and_field

//=====================================================

public function register_setting_and_field(){

register_setting(

'lionel_setting_options',

'lionel_option',

array($this, 'validate_setting')

);

$mainSection = 'lionel_main_section';

add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);

$extSection = 'lionel_ext_section';

add_settings_section('lionel_ext_section', 'Slogan', '', $this->_menuSlug);

add_settings_field('lionel_new_title','

Site Title', array($this, 'create_form'), $this->_menuSlug, $mainSection, array('name'=>'new_title_input'));

add_settings_field('lionel_new_slogan','

Slogan Title', array($this, 'create_form'), $this->_menuSlug, $extSection, array('name'=>'new_slogan_input'));

}

public function create_form($args){

if($args['name']== 'new_title_input'){

echo '<input type="text" name="lionel_option[lionel_new_title]"

value="' . $this->_setting_option['lionel_new_title'] . '"/>';

echo '<p class="description">Nhập vào một chuỗi không quá 20 ký tự</p>';

}

if($args['name']== 'new_slogan_input'){

echo '<input type="text" name="lionel_option[lionel_new_slogan]"

value="' . $this->_setting_option['lionel_new_slogan'] . '"/>';

echo '<p class="description">Nhập vào một chuỗi không quá 20 ký tự</p>';

}

}

//=====================================================

// Phương thức validate_setting

//=====================================================

public function validate_setting($data_input){

$errors = array();

if($this->stringMaxValidate($data_input['lionel_new_title'], 20) == false){

$errors['lionel_new_title'] = "Tiêu đề quá số ký tự cho phép";

}

if($this->stringMaxValidate($data_input['lionel_new_slogan'], 20) == false){

$errors['lionel_new_slogan'] = "Slogan quá số ký tự cho phép";

}

// Nếu $errors lớn hơn 0 tức là xảy ra lỗi.

if(count($errors)>0){

$data_input = $this->_setting_options;

$strErrors = '';

foreach ($errors as $key => $val){

$strErrors .= $val . '<br/>';

}

//die();

// Xuất ra thông báo lỗi khi xảy ra lỗi

add_settings_error($this->_menuSlug, 'my-setting', $strErrors,'error');

}else{

// Xuất ra thông báo thành công

add_settings_error($this->_menuSlug, 'my-setting', 'Cap nhat du lieu thanh cong','updated');

}

//die();

return $data_input;

}

//=====================================================

// Kiểm tra độ dài ký tự

//=====================================================

private function stringMaxValidate($val, $max){

$flag = false;

$str = trim($val);

if(strlen($str) <= $max){

$flag = true;

}

return $flag;

}

//=====================================================

// Phương thức settingMenu (Khởi tạo menu Lionel Setting)

//=====================================================

public function settingMenu(){

add_menu_page(

'My Setting Page',

'Lionel Setting',

'manage_options'

,$this->_menuSlug,

array($this, 'settingPage')

);

}

//=====================================================

// Phương thức settingPage gọi tới views hiển thị nội dung

//=====================================================

public function settingPage(){

require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';

}

}

Để hiển thị thông báo lỗi thì trong file setting-page.php bạn sẽ phải gọi thêm phương thức settings_errors( $this->_menuSlug, false, false ), false để hiển thị cả phần error lẫn phần update.

1

2

3

4

5

6

7

8

9

10

11

12

<div class="wrap">

<h2>My Setting page</h2>

<?php settings_errors( $this->_menuSlug, false, false );?>

<p>Đây là trang thiết lập cấu hình plugin Lionel Setting</p>

<form method="post" action="options.php" id="lionel_setting_form" enctype="multipart/form-data" >

<?php settings_fields('lionel_setting_options'); ?>

<?php do_settings_sections($this->_menuSlug); ?>

<p class="submit">

<input type="submit" name="submit" class="button button-primary" value="Save Changes">

</p>

</form>

</div>

Bây giờ nếu cập nhật thành công sẽ có thông báo trả về, và dữ liệu không được lưu vào database. Còn lại nếu dữ liệu nhập vào hợp lệ thì trình duyêt sẽ thông báo “Cap nhat du lieu thanh cong”.

5/ Kết bài

Hy vọng thông qua bài Sử dụng WordPress Setting API toàn tập – P2 thì bạn đã hiểu rõ quy tắc nhập liệu từ form để lưu dữ liệu vào database do WordPress đề ra nó phức tạp như thế nào. Tuy nhiên đây vẫn chưa được gọi là vấn đề khó nhất, con đường chinh phục WordPress còn rất dài, bạn nên chuẩn bị sẵn tâm lý mà đón nhận những vấn đề khó hơn ở căc bài kế tiếp.

Series Navigation<< Sử dụng WordPress Setting API toàn tập – P1Khái niệm về WordPress Widget API >>

Nguồn: laptrinhweb.org

Xem thêm ví dụ 1:

https://gist.github.com/DavidWells/4653358

<?php
/*
Plugin Name: Homepage Settings for BigBang
Plugin URI: http://www.inboundnow.com/
Description: Adds additional functionality to the big bang theme.
Author: David Wells
Author URI: http://www.inboundnow.com
*/

// Specify Hooks/Filters
register_activation_hook(__FILE__, 'add_defaults_fn');
add_action('admin_init', 'sampleoptions_init_fn' );
add_action('admin_menu', 'sampleoptions_add_page_fn');

// Define default option settings
function add_defaults_fn() {
	$tmp = get_option('plugin_options');
    if(($tmp['chkbox1']=='on')||(!is_array($tmp))) {
		$arr = array("dropdown1"=>"Orange", "text_area" => "Space to put a lot of information here!", "text_string" => "Some sample text", "pass_string" => "123456", "chkbox1" => "", "chkbox2" => "on", "option_set1" => "Triangle");
		update_option('plugin_options', $arr);
	}
}

// Register our settings. Add the settings section, and settings fields
function sampleoptions_init_fn(){
	register_setting('plugin_options', 'plugin_options', 'plugin_options_validate' );
	add_settings_section('main_section', 'Main Settings', 'section_text_fn', __FILE__);
	add_settings_field('plugin_text_string', 'Text Input', 'setting_string_fn', __FILE__, 'main_section');
	add_settings_field('plugin_text_pass', 'Password Text Input', 'setting_pass_fn', __FILE__, 'main_section');
	add_settings_field('plugin_textarea_string', 'Large Textbox!', 'setting_textarea_fn', __FILE__, 'main_section');
	add_settings_field('plugin_chk2', 'A Checkbox', 'setting_chk2_fn', __FILE__, 'main_section');
	add_settings_field('radio_buttons', 'Select Shape', 'setting_radio_fn', __FILE__, 'main_section');
	add_settings_field('radio_buttons', 'Home Page Boxes', 'setting_visual_fn', __FILE__, 'main_section');
	add_settings_field('drop_down1', 'Select Color', 'setting_dropdown_fn', __FILE__, 'main_section');
	add_settings_field('plugin_chk1', 'Restore Defaults Upon Reactivation?', 'setting_chk1_fn', __FILE__, 'main_section');
}

// Add sub page to the Settings Menu
function sampleoptions_add_page_fn() {
// add optiont to main settings panel
 add_options_page('Big Bang Extra Settings', 'BigBang Settings', 'administrator', __FILE__, 'options_page_fn');

}

// ************************************************************************************************************

// Callback functions

// Init plugin options to white list our options

// Section HTML, displayed before the first option
function  section_text_fn() {
	echo '<p>Below are some examples of different option controls.</p>';
}

// DROP-DOWN-BOX - Name: plugin_options[dropdown1]
function  setting_dropdown_fn() {
	$options = get_option('plugin_options');
	$items = array("Red", "Green", "Blue", "Orange", "White", "Violet", "Yellow");
	echo "<select id='drop_down1' name='plugin_options[dropdown1]'>";
	foreach($items as $item) {
		$selected = ($options['dropdown1']==$item) ? 'selected="selected"' : '';
		echo "<option value='$item' $selected>$item</option>";
	}
	echo "</select>";
}

// TEXTAREA - Name: plugin_options[text_area]
function setting_textarea_fn() {
	$options = get_option('plugin_options');
	echo "<textarea id='plugin_textarea_string' name='plugin_options[text_area]' rows='7' cols='50' type='textarea'>{$options['text_area']}</textarea>";
}

// TEXTBOX - Name: plugin_options[text_string]
function setting_string_fn() {
	$options = get_option('plugin_options');
	echo "<input id='plugin_text_string' name='plugin_options[text_string]' size='40' type='text' value='{$options['text_string']}' />";
}

// PASSWORD-TEXTBOX - Name: plugin_options[pass_string]
function setting_pass_fn() {
	$options = get_option('plugin_options');
	echo "<input id='plugin_text_pass' name='plugin_options[pass_string]' size='40' type='password' value='{$options['pass_string']}' />";
}

// CHECKBOX - Name: plugin_options[chkbox1]
function setting_chk1_fn() {
	$options = get_option('plugin_options');
	if($options['chkbox1']) { $checked = ' checked="checked" '; }
	echo "<input ".$checked." id='plugin_chk1' name='plugin_options[chkbox1]' type='checkbox' />";
}

// CHECKBOX - Name: plugin_options[chkbox2]
function setting_chk2_fn() {
	$options = get_option('plugin_options');
	if($options['chkbox2']) { $checked = ' checked="checked" '; }
	echo "<input ".$checked." id='plugin_chk2' name='plugin_options[chkbox2]' type='checkbox' />";
}

// RADIO-BUTTON - Name: plugin_options[option_set1]
function setting_radio_fn() {
	$options = get_option('plugin_options');
	$items = array("Square", "Triangle", "Circle");
	foreach($items as $item) {
		$checked = ($options['option_set1']==$item) ? ' checked="checked" ' : '';
		echo "<label><input ".$checked." value='$item' name='plugin_options[option_set1]' type='radio' /> $item</label><br />";
	}
}
// WYSIWYG Visual Editor - Name: plugin_options[textarea_one]
function setting_visual_fn() {
	$options = get_option('plugin_options');
	$args = array("textarea_name" => "plugin_options[textarea_one]");
	wp_editor( $options['textarea_one'], "plugin_options[textarea_one]", $args );
	
// Add another text box
	$options = get_option('plugin_options');
	$args = array("textarea_name" => "plugin_options[textarea_two]");
	wp_editor( $options['textarea_two'], "plugin_options[textarea_two]", $args );				
	}		

// Sanitize and validate input. Accepts an array, return a sanitized array.
function wpet_validate_options($input) {
	// Sanitize textarea input (strip html tags, and escape characters)
	//$input['textarea_one'] = wp_filter_nohtml_kses($input['textarea_one']);
	//$input['textarea_two'] = wp_filter_nohtml_kses($input['textarea_two']);
	//$input['textarea_three'] = wp_filter_nohtml_kses($input['textarea_three']);
	return $input;
}
// Display the admin options page
function options_page_fn() {
?>
	<div class="wrap">
		<div class="icon32" id="icon-options-general"><br></div>
		<h2>My Example Options Page</h2>
		Some optional text here explaining the overall purpose of the options and what they relate to etc.
		<form action="options.php" method="post">
					<?php
if ( function_exists('wp_nonce_field') ) 
	wp_nonce_field('plugin-name-action_' . "yep"); 
?>
		<?php settings_fields('plugin_options'); ?>
		<?php do_settings_sections(__FILE__); ?>
		<p class="submit">
			<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
		</p>
		</form>
	</div>
<?php
}

// Validate user data for some/all of your input fields
function plugin_options_validate($input) {
	// Check our textbox option field contains no HTML tags - if so strip them out
	$input['text_string'] =  wp_filter_nohtml_kses($input['text_string']);	
	return $input; // return validated input
}

Xem thêm ví dụ 2:

https://wordpress.stackexchange.com/questions/261560/adding-an-html-editor-to-plugin-settings-page

Xem thêm ví dụ 3:

<?php
class LionelBackend {
  private $_menuSlug = 'lionel-my-setting';
  private $_setting_option;
  public function __construct() {
    //=====================================================
    // Biến toàn cục $_setting_option giúp bạn lấy ra các giá trị trong field lionel_option
    //=====================================================
    $this->_setting_option = get_option('lionel_option', []);
    //=====================================================
    // Gọi Hook admin_menu xử lý và khởi tạo menu mới
    //=====================================================
    add_action('admin_menu', [$this, 'settingMenu']);
    //=====================================================
    // Gọi Hook admin_init để khởi tạo và xử lý phương thức
    //=====================================================
    add_action('admin_init', [$this, 'register_setting_and_field']);
  }
  //=====================================================
  // Phương thức register_setting_and_field
  //=====================================================
  public function register_setting_and_field() {
    register_setting(
      'lionel_setting_options',
      'lionel_option',
      [$this, 'validate_setting']
    );
    $mainSection = 'lionel_main_section';
    $extSection = 'lionel_ext_section';
    $colorSection = 'lionel_color_section';
    add_settings_section('lionel_main_section', 'Setting Title', '', $this->_menuSlug);
    add_settings_section('lionel_ext_section', 'Slogan', '', $this->_menuSlug);
    add_settings_section('lionel_color_section', 'Color', '', $this->_menuSlug);
    add_settings_field('lionel_new_title', 'Site Title', [$this, 'create_form'], $this->_menuSlug, $mainSection, ['name' => 'new_title_input']);
    add_settings_field('lionel_new_slogan', 'Slogan Title', [$this, 'create_form'], $this->_menuSlug, $extSection, ['name' => 'new_slogan_input']);
    add_settings_field('lionel_new_color', 'Select Color', [$this, 'create_form'], $this->_menuSlug, $colorSection,['name' => 'new_color_input']);
  }
  public function create_form($args) {
    if ($args['name'] == 'new_title_input') {
      echo '<input type="text" name="lionel_option[lionel_new_title]" value="' . $this->_setting_option['lionel_new_title'] . '"/>';
      echo '<p class="description">Nhập vào một chuỗi không quá 20 ký tự</p>';
    }
    if ($args['name'] == 'new_slogan_input') {
      echo '<input type="text" name="lionel_option[lionel_new_slogan]" value="' . $this->_setting_option['lionel_new_slogan'] . '"/>';
      echo '<p class="description">Nhập vào một chuỗi không quá 20 ký tự</p>';
    }
    if ($args['name'] == 'new_color_input') {
      $options = get_option('lionel_option');
			$items = array("Red", "Green", "Blue", "Orange", "White", "Violet", "Yellow");
			echo "<select id='lionel_new_color' name='lionel_option[lionel_new_color]'>";
			foreach($items as $item) {
				$selected = ($options['dropdown1']==$item) ? 'selected="selected"' : '';
				echo "<option value='$item' $selected>$item</option>";
			}
			echo "</select>";
    }

  }
  public function validate_setting($data_input) {
    $errors = [];
    if ($this->stringMaxValidate($data_input['lionel_new_title'], 20) == false) {
      $errors['lionel_new_title'] = "Tiêu đề quá số ký tự cho phép";
    }
    if ($this->stringMaxValidate($data_input['lionel_new_slogan'], 20) == false) {
      $errors['lionel_new_slogan'] = "Slogan quá số ký tự cho phép";
    }
    if (count($errors) > 0) {
      $data_input = $this->_setting_options;
      $strErrors  = '';
      foreach ($errors as $key => $val) {
        $strErrors .= $val . '<br/>';
      }
      add_settings_error($this->_menuSlug, 'my-setting', $strErrors, 'error');
    } else {
      add_settings_error($this->_menuSlug, 'my-setting', 'Cap nhat du lieu thanh cong', 'updated');
    }
    return $data_input;
  }
  private function stringMaxValidate($val, $max) {
    $flag = false;
    $str  = trim($val);
    if (strlen($str) <= $max) {
      $flag = true;
    }
    return $flag;
  }
  public function settingMenu() {
    add_menu_page(
      'My Setting Page',
      'Lionel Setting',
      'manage_options'
      , $this->_menuSlug,
      [$this, 'settingPage']
    );
  }
  public function settingPage() {
    require_once LIONEL_SETTING_VIEWS_DIR . '/setting-page.php';
  }
}

Last updated