How to add taxonomy images in WordPress without Plugin?
Step1: Add the Image Field
add_action( 'category_add_form_fields', 'add_category_image', 10, 2 );
function add_category_image ( $taxonomy ) {
?>
Step2: Save the Image Field
add_action( 'created_category', 'save_category_image', 10, 2 );
function save_category_image ( $term_id, $tt_id ) {
if( isset( $_POST['image_id'] ) && '' !== $_POST['image_id'] ){
$image = $_POST['image_id'];
add_term_meta( $term_id, 'category_image_id', $image, true );
}
}
Step3: Add the Image Field in the Edit Form
add_action( 'category_edit_form_fields', 'update_category_image', 10, 2 );
function update_category_image ( $term, $taxonomy ) { ?>
}
Step4: Update the Image Field
add_action( 'edited_category', 'updated_category_image', 10, 2 );
function updated_category_image ( $term_id, $tt_id ) {
if( isset( $_POST['image_id'] ) && '' !== $_POST['image_id'] ){
$image = $_POST['image_id'];
update_term_meta ( $term_id, 'image_id', $image );
} else {
update_term_meta ( $term_id, 'image_id', '' );
}
}
Step5: Enqueue Media Library
add_action( 'admin_enqueue_scripts', 'load_media' );
function load_media() {
wp_enqueue_media();
}
Step6: Display the Image in Column
add_filter( 'manage_edit-category_columns', 'display_image_column_heading' );
function display_image_column_heading( $columns ) {
$columns['category_image'] = __( 'Image' );
return $columns;
}
Step7: Display the Image on Frontend
$image_id = get_term_meta ( $term_id, 'image_id', true ); echo wp_get_attachment_image ( $image_id, 'full' );