Thêm ảnh đại diện cho category wordpress

ảnh địa diện cho category wordpress
5/5 - (1 vote)

Mặc định thì category trong wordpress chỉ có tên danh mục và mô tả hiển thị ra ngoài giao diện người dùng. Nên muốn hiển thị ảnh đại diện cho category ở trong danh mục bài đăng trong wordpress phải đành ngậm ngùi.

Tuy nhiên bạn không cần phải quá lo lắng vì có rất nhiều plugin hỗ trợ giúp bạn chèn ảnh ảnh đại diện cho danh mục bài đăng trong wordpress. Còn nếu bạn không thích nhờ vã đến sự trợ giúp của plugin vì nó làm chậm website của bạn thì đừng lo dưới đây là cách giúp bạn thêm ảnh đại diện cho category không cần dùng plugin mà bạn cần.

Thêm trường hiển thị hình ảnh đại diện trong category wordpress

Khi bạn bấm vào trang quản trị category trong wp-admin thì không thấy bất cứ chỗ nào để thêm hình ảnh đại diện vào cho category. Vì vậy đây bước quan trọng đầu tiên chúng ta cần phải làm để có thể hiển thị hình ảnh đại diện trong category wordpress.

public function add_category_image ( $taxonomy ) { ?>
    <div class="form-field term-group">
        <label for="category-image-id"><?php _e('Image', 'hero-theme'); ?></label>
        <input type="hidden" id="category-image-id" name="category-image-id" class="custom_media_url" value="">
        <div id="category-image-wrapper"><p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p></div>
        <p>
        <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
        <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
        </p>
    </div>
    <?php
}

Trong đoạn code trên chúng ta sẽ cho hiển thị ra một nút thêm hình ảnh để thêm hình ảnh vào làm ảnh đại diện cho category và một nút xóa hình ảnh để xóa bỏ hình ảnh khi không muốn hiển thị hình ảnh trong category.

Để chúng trông đẹp hơn khi không có hình ảnh thì ta chèn thêm một đoạn code trong thẻ <div> và đặt id cho nó là “category-image-wrapper”. Và phần này cũng chỉnh là phần chúng ta hiển thị hình ảnh sau khi thêm ảnh vào.

Lưu ảnh đại diện cho category

Sau khi thêm trường thêm hình ảnh đại diện cho category thì bạn cần phải lưu nó lại trên hệ thống để có thể sử dụng hình ảnh đó hiển thị ra ngoài giao diện người dùng phải không nào. Nếu bạn không lưu hình ảnh thì sau khi bạn refresh trang mọi thứ sẽ trở về con số 0.

public function save_category_image ( $term_id, $tt_id ) {
    if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
        $image = $_POST['category-image-id'];
        add_term_meta( $term_id, 'category-image-id', $image, true );
    }
}

Chỉnh sửa hình ảnh đại diện cho category

Khi bạn lưu ảnh thành công rồi nhưng lại thấy không vừa ý thì việc bạn nghĩ ngay đến đó là đổi ảnh đó bằng một ảnh khác ưng ý hơn. Nên bạn cần phải code thêm chức năng chỉnh sửa ảnh đại diện để có thể thay đổi hình ảnh mới cho category của bạn.

public function update_category_image ( $term, $taxonomy ) { ?>
    <tr class="form-field term-group-wrap">
        <th scope="row">
        <label for="category-image-id"><?php _e( 'Image', 'hero-theme' ); ?></label>
        </th>
        <td>
        <?php $image_id = get_term_meta ( $term -> term_id, 'category-image-id', true ); ?>
        <input type="hidden" id="category-image-id" name="category-image-id" value="<?php echo $image_id; ?>">
        <div id="category-image-wrapper">
            <?php if ( $image_id ) { ?>
            <?php echo wp_get_attachment_image ( $image_id, 'thumbnail' ); ?>
            <?php }else{ ?>
                <p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>
            <?php } ?>
        </div>
        <p>
            <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
            <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
        </p>
        </td>
    </tr>
    <?php
}

Và đã chỉnh sửa xong thì cập nhật thông tin đã chỉnh sửa để nó thay thế hình ảnh cũ đã được bạn lưu vào hệ thống trước đó.

public function updated_category_image ( $term_id, $tt_id ) {
    if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
        $image = $_POST['category-image-id'];
        update_term_meta ( $term_id, 'category-image-id', $image );
    } else {
        update_term_meta ( $term_id, 'category-image-id', '' );
    }
}

Mở thư viện hình ảnh để upload hình ảnh lên wordpress

Trong wordpress để thêm hình ảnh vào hệ thống bạn phải thông qua thư viện media của nó, vì vậy những phần ở trên chưa thể là được gì cả vì bạn có bấm vào nút thêm ảnh thì cũng chã có điều gì hiện ra.

Nên bạn cần phải nhờ đến sự trợ giúp của đoạn script dưới đây để gọi thư viện hình ảnh trong wordpress rồi từ đó mới có thể upload hình ảnh lên và lưu hình ảnh vào hệ thống để mới có thể hiển thị lên giao diện người dùng.

public function add_script() { ?>
    <script>
        jQuery(document).ready( function($) {
            function ct_media_upload(button_class) {
                var _custom_media = true,
                _orig_send_attachment = wp.media.editor.send.attachment;
                $('body').on('click', button_class, function(e) {
                    var button_id = '#'+$(this).attr('id');
                    var send_attachment_bkp = wp.media.editor.send.attachment;
                    var button = $(button_id);
                    _custom_media = true;
                    wp.media.editor.send.attachment = function(props, attachment){
                        if ( _custom_media ) {
                        $('#category-image-id').val(attachment.id);
                        $('#category-image-wrapper').html('<img class="custom_media_image" src="" style="margin:10px 0;padding:0;max-height:100px;float:none;" />');
                        $('#category-image-wrapper .custom_media_image').attr('src',attachment.url).css('display','block');
                        } else {
                        return _orig_send_attachment.apply( button_id, [props, attachment] );
                        }
                    }
                    wp.media.editor.open(button);
                    return false;
                });
            }
            ct_media_upload('.ct_tax_media_button.button'); 
            $('body').on('click','.ct_tax_media_remove',function(){
                $('#category-image-id').val('');
                $('#category-image-wrapper').html('<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>');
            });
            // Thanks: http://stackoverflow.com/questions/15281995/wordpress-create-category-ajax-response
            $(document).ajaxComplete(function(event, xhr, settings) {
                var queryStringArr = settings.data.split('&');
                if( $.inArray('action=add-tag', queryStringArr) !== -1 ){
                    var xml = xhr.responseXML;
                    $response = $(xml).find('term_id').text();
                    if($response!=""){
                    // Clear the thumb image
                    $('#category-image-wrapper').html('<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>');
                    }
                }
            });
        });
    </script>
<?php }

Code hoàn chỉnh thêm ảnh đại diện cho category wordpress

Thêm ảnh đại diện cho category wordpress
Thêm ảnh đại diện cho category wordpress

Chắc đây sẽ là phần bạn mong đợi nhất trong toàn bộ bài viết này đó là code full để giúp thêm hình ảnh đại diện cho category trong wordpress.

if ( ! class_exists( 'CT_TAX_META' ) ) {

   class CT_TAX_META {
	
        public function __construct() {
            //
        }
        
        /*
        * Initialize the class and start calling our hooks and filters
        * @since 1.0.0
        */
        public function init() {
            add_action( 'category_add_form_fields', array ( $this, 'add_category_image' ), 10, 2 );
            add_action( 'created_category', array ( $this, 'save_category_image' ), 10, 2 );
            add_action( 'category_edit_form_fields', array ( $this, 'update_category_image' ), 10, 2 );
            add_action( 'edited_category', array ( $this, 'updated_category_image' ), 10, 2 );
            add_action( 'admin_enqueue_scripts', array( $this, 'load_media' ) );
            add_action( 'admin_footer', array ( $this, 'add_script' ) );
        }
        
        public function load_media() {
            wp_enqueue_media();
        }
        
        /*
        * Add a form field in the new category page
        * @since 1.0.0
        */
        public function add_category_image ( $taxonomy ) { ?>
            <div class="form-field term-group">
                <label for="category-image-id"><?php _e('Image', 'hero-theme'); ?></label>
                <input type="hidden" id="category-image-id" name="category-image-id" class="custom_media_url" value="">
                <div id="category-image-wrapper"><p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p></div>
                <p>
                <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
                <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
                </p>
            </div>
            <?php
        }
        
        /*
        * Save the form field
        * @since 1.0.0
        */
        public function save_category_image ( $term_id, $tt_id ) {
            if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
                $image = $_POST['category-image-id'];
                add_term_meta( $term_id, 'category-image-id', $image, true );
            }
        }
        
        /*
        * Edit the form field
        * @since 1.0.0
        */
        public function update_category_image ( $term, $taxonomy ) { ?>
            <tr class="form-field term-group-wrap">
                <th scope="row">
                <label for="category-image-id"><?php _e( 'Image', 'hero-theme' ); ?></label>
                </th>
                <td>
                <?php $image_id = get_term_meta ( $term -> term_id, 'category-image-id', true ); ?>
                <input type="hidden" id="category-image-id" name="category-image-id" value="<?php echo $image_id; ?>">
                <div id="category-image-wrapper">
                    <?php if ( $image_id ) { ?>
                    <?php echo wp_get_attachment_image ( $image_id, 'thumbnail' ); ?>
                    <?php }else{ ?>
                        <p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>
                    <?php } ?>
                </div>
                <p>
                    <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
                    <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
                </p>
                </td>
            </tr>
            <?php
        }
        
        /*
        * Update the form field value
        * @since 1.0.0
        */
        public function updated_category_image ( $term_id, $tt_id ) {
            if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
                $image = $_POST['category-image-id'];
                update_term_meta ( $term_id, 'category-image-id', $image );
            } else {
                update_term_meta ( $term_id, 'category-image-id', '' );
            }
        }
        
        /*
        * Add script
        * @since 1.0.0
        */
        public function add_script() { ?>
            <script>
                jQuery(document).ready( function($) {
                    function ct_media_upload(button_class) {
                        var _custom_media = true,
                        _orig_send_attachment = wp.media.editor.send.attachment;
                        $('body').on('click', button_class, function(e) {
                            var button_id = '#'+$(this).attr('id');
                            var send_attachment_bkp = wp.media.editor.send.attachment;
                            var button = $(button_id);
                            _custom_media = true;
                            wp.media.editor.send.attachment = function(props, attachment){
                                if ( _custom_media ) {
                                $('#category-image-id').val(attachment.id);
                                $('#category-image-wrapper').html('<img class="custom_media_image" src="" style="margin:10px 0;padding:0;max-height:100px;float:none;" />');
                                $('#category-image-wrapper .custom_media_image').attr('src',attachment.url).css('display','block');
                                } else {
                                return _orig_send_attachment.apply( button_id, [props, attachment] );
                                }
                            }
                            wp.media.editor.open(button);
                            return false;
                        });
                    }
                    ct_media_upload('.ct_tax_media_button.button'); 
                    $('body').on('click','.ct_tax_media_remove',function(){
                        $('#category-image-id').val('');
                        $('#category-image-wrapper').html('<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>');
                    });
                    // Thanks: http://stackoverflow.com/questions/15281995/wordpress-create-category-ajax-response
                    $(document).ajaxComplete(function(event, xhr, settings) {
                        var queryStringArr = settings.data.split('&');
                        if( $.inArray('action=add-tag', queryStringArr) !== -1 ){
                            var xml = xhr.responseXML;
                            $response = $(xml).find('term_id').text();
                            if($response!=""){
                            // Clear the thumb image
                            $('#category-image-wrapper').html('<p style="background-color: #edeff0; border: 1px dashed #b4b9be; line-height:90px;text-align:center">Category image</p>');
                            }
                        }
                    });
                });
            </script>
        <?php }
	
	  }
	 
	$CT_TAX_META = new CT_TAX_META();
	$CT_TAX_META -> init();
	 
}

Cho bạn nào chưa rành về wordpress thì hãy thêm đoạn code trên vào phần cuối dưới cùng nhất của file function.php nhé.

Và để hiển thị hình ảnh ra ngoài giao diện người dùng bạn dùng đoạn code sau và đặt chúng vào vị trí mà bạn mong muốn hình ảnh hiện ra.

// Get the current category ID, e.g. if we're on a category archive page
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;
// Get the image ID for the category
$image_id = get_term_meta ( $cat_id, 'category-image-id', true );
// Echo the image
echo wp_get_attachment_image ( $image_id, 'large' );

Như vậy là chúng ta đã có thể thêm ảnh đại diện cho category wordpress một cách nhanh chóng mà không cần phải nhờ để plugin hỗ trợ rồi.

Để lại bình luận

Email của bạn sẽ được bảo mật.