Thêm custom field vào form thêm danh mục mới

Bạn copy đoạn code này vào file functions.php

// Thêm custom field vào form thêm danh mục
function add_product_cat_image_field() {
    ?>
    <div class="form-field">
        <label for="product_cat_image"><?php _e('Ảnh đại diện', 'giuseart.com'); ?></label>
        <input type="text" name="product_cat_image" id="product_cat_image" value="">
        <button class="button" id="product_cat_image_button"><?php _e('Tải ảnh lên', 'giuseart.com'); ?></button>
        <p class="description"><?php _e('Tải ảnh đại diện cho danh mục này', 'giuseart.com'); ?></p>
        <div id="product_cat_image_preview" style="margin-top: 10px;"></div>
    </div>
    <script>
        jQuery(document).ready(function($){
            var mediaUploader;
            $('#product_cat_image_button').click(function(e) {
                e.preventDefault();
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }
                mediaUploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    }, 
                    multiple: false
                });
                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    $('#product_cat_image').val(attachment.url);
                    $('#product_cat_image_preview').html('<img src="' + attachment.url + '" style="max-width: 100%; height: auto;">');
                });
                mediaUploader.open();
            });
        });
    </script>
    <?php
}
add_action('product_cat_add_form_fields', 'add_product_cat_image_field', 10, 2);

Thêm custom field vào form chỉnh sửa danh mục đã có

Bạn tiếp tục thêm đoạn code này vào function.php

// Thêm custom field vào form chỉnh sửa danh mục
function edit_product_cat_image_field($term) {
    $product_cat_image = get_term_meta($term->term_id, 'product_cat_image', true);
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="product_cat_image"><?php _e('Ảnh đại diện', 'giuseart.com'); ?></label></th>
        <td>
            <input type="text" name="product_cat_image" id="product_cat_image" value="<?php echo esc_attr($product_cat_image); ?>">
            <button class="button" id="product_cat_image_button"><?php _e('Tải ảnh lên', 'giuseart.com'); ?></button>
            <p class="description"><?php _e('Tải ảnh đại diện cho danh mục này', 'giuseart.com'); ?></p>
            <div id="product_cat_image_preview" style="margin-top: 10px;">
                <?php if ($product_cat_image) : ?>
                    <img src="<?php echo esc_url($product_cat_image); ?>" style="max-width: 100%; height: auto;">
                <?php endif; ?>
            </div>
            <script>
                jQuery(document).ready(function($){
                    var mediaUploader;
                    $('#product_cat_image_button').click(function(e) {
                        e.preventDefault();
                        if (mediaUploader) {
                            mediaUploader.open();
                            return;
                        }
                        mediaUploader = wp.media.frames.file_frame = wp.media({
                            title: 'Choose Image',
                            button: {
                                text: 'Choose Image'
                            }, 
                            multiple: false
                        });
                        mediaUploader.on('select', function() {
                            var attachment = mediaUploader.state().get('selection').first().toJSON();
                            $('#product_cat_image').val(attachment.url);
                            $('#product_cat_image_preview').html('<img src="' + attachment.url + '" style="max-width: 100%; height: auto;">');
                        });
                        mediaUploader.open();
                    });
                });
            </script>
        </td>
    </tr>
    <?php
}
add_action('product_cat_edit_form_fields', 'edit_product_cat_image_field', 10, 2);

Lưu vào database

Tiếp tục, bạn thêm code vào file functions.php nhé

// Lưu giá trị của custom field khi tạo mới danh mục
function save_product_cat_image_field($term_id) {
    if (isset($_POST['product_cat_image']) && '' !== $_POST['product_cat_image']) {
        update_term_meta($term_id, 'product_cat_image', sanitize_text_field($_POST['product_cat_image']));
    }
}
add_action('created_product_cat', 'save_product_cat_image_field', 10, 2);
 
// Lưu giá trị của custom field khi chỉnh sửa danh mục
function update_product_cat_image_field($term_id) {
    if (isset($_POST['product_cat_image']) && '' !== $_POST['product_cat_image']) {
        update_term_meta($term_id, 'product_cat_image', sanitize_text_field($_POST['product_cat_image']));
    } else {
        delete_term_meta($term_id, 'product_cat_image');
    }
}
add_action('edited_product_cat', 'update_product_cat_image_field', 10, 2);

Hiển thị ảnh đại diện ra ngoài trình duyệt

Nếu bạn muốn thêm vào file function thì dùng đoạn code này:

// Display the category image on the front end
function display_product_cat_image() {
    if (is_tax('product_cat')) {
        $term = get_queried_object();
        $image_url = get_term_meta($term->term_id, 'product_cat_image', true);
        if ($image_url) {
            echo '<div class="product-category-image">';
            echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($term->name) . '">';
            echo '</div>';
        }
    }
}
add_action('woocommerce_before_main_content', 'display_product_cat_image', 15);

Nếu bạn muốn đặt ảnh đại diện ở một vị trí tùy chọn trong tệp template của theme, bạn có thể sử dụng đoạn code dưới đây. Lưu ý rằng cấu trúc hiển thị có thể khác nhau giữa các theme. Ví dụ, với theme Flatsome, bạn có thể tìm các file trong thư mục woocommerce/layout/, nơi chứa các layout của trang danh mục sản phẩm. Sau khi xác định vị trí muốn hiển thị, chỉ cần dán mã vào đúng chỗ là xong.

custom field ảnh đại diện cho danh mục sản phẩm

Ảnh bên trên là tôi dùng theme Flatsome, bạn chỉ cần thêm đoạn code vào trên cùng là được nhé.

<?php 
if (is_tax('product_cat')) {
        $term = get_queried_object();
        $image_url = get_term_meta($term->term_id, 'product_cat_image', true);
        if ($image_url) {
            echo '<div class="product-category-image">';
            echo '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($term->name) . '">';
            echo '</div>';
        }
}?>

Và đây là kết quả.

custom field ảnh đại diện cho danh mục sản phẩm

Như thế là đã hoàn thành rồi. Chúc bạn thành công!

Bạn đã tới tận cùng thế giới!
Contact