Skip to main content

Thêm field vào Taxonomy Terms trong WordPress

Đây là hướng dẫn tạo thêm field vào trong Taxonomy Term trong WordPress như hình bên dưới

Image
thêm field vào taxônmy term wp

 

Thêm fields vào trong Add New Taxonomy Term 

Để thêm trường trên vị trí Add New chúng ta dùng một hook "{Taxonomy}_add_form_fields"  để hiển thị trường mới của chúng ta

add_action( 'post_tag_add_form_fields', 'misha_add_term_fields' );
 
function misha_add_term_fields( $taxonomy ) {
 
	echo '<div class="form-field">
	<label for="misha-text">Text Field</label>
	<input type="text" name="misha-text" id="misha-text" />
	<p>Field description may go here.</p>
	</div>';
 
}

Giải thích: 

 Đoạn code trên là thêm 1 trường vào taxonomy type "post_tag" do đó nên dùng hook post_tag_add_form_fields. Bạn có thể thay đổi phù hợp với taxonomy bạn muốn

Kết quả là 

Image
thêm field vào taxônmy term wp

Hiển thị fields vào trong Edit Term 

Tương tự như bước trên nhưng chúng ta sẽ dùng một hook khác tên là "{Taxonomy}_edit_form_fields"

add_action( 'post_tag_edit_form_fields', 'misha_edit_term_fields', 10, 2 );
 
function misha_edit_term_fields( $term, $taxonomy ) {
 
	$value = get_term_meta( $term->term_id, 'misha-text', true );
 
	echo '<tr class="form-field">
	<th>
		<label for="misha-text">Text Field</label>
	</th>
	<td>
		<input name="misha-text" id="misha-text" type="text" value="' . esc_attr( $value ) .'" />
		<p class="description">Field description may go here.</p>
	</td>
	</tr>';
 
}

Giải thích: 

Function có hai parameters :  $term là đối tượng term mà mình đanh edit và $taxonomy là taxonomy name. Và dùng get_term_meta() để lấy data của term

Ta sẽ được kết quả 

Image
Hiển thị fields vào trong Edit Term 

 

Cuối cùng là lưu dữ liệu của Fields 

Sử dụng hai hook là created_{Taxonomy} và edited_{Taxonomy} để lưu lại dữ liệu của term

add_action( 'created_post_tag', 'misha_save_term_fields' );
add_action( 'edited_post_tag', 'misha_save_term_fields' );
 
function misha_save_term_fields( $term_id ) {
 
	update_term_meta(
		$term_id,
		'misha-text',
		sanitize_text_field( $_POST[ 'misha-text' ] )
	);
 
}