Chào mừng đến với Diễn Đàn Tin Học VN! Hãy chia sẽ những gì bạn biết, và đưa ra thắc mắc của bạn để được giải đáp.

Xem chủ đề cũ hơnGo downXem chủ đề mới hơn
phoenix51706
phoenix51706
Admin
Tổng số bài gửi : 171
Join date : 30/07/2010
https://diendantinhocvn.forumvi.com

Thêm thumbnail cho category trong wordpress Empty Thêm thumbnail cho category trong wordpress

14/12/21, 07:06 pm
Code để xử lý thêm ảnh cho category

Code:
/*******************************************
 * Add thumbnail to category
 *******************************************/

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();
 
 }

code để hiển thị hình ảnh của category ra ngoài trang web (frondend)
Code:

//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' );

If you want to get category id of any particular category on any page, try using :
Nếu muốn lấy category id của bất cứ category nào để đặt tại bất cứ đâu thì chỉnh sửa đoạn code trên thành

Code:
//If you want to get category id of any particular category on any page
$cat_id = get_cat_ID('Category Name');
// 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' );

code hiển thị tất cả category
Code:
<div class="recent-post">
              
              <?php
                  $categories = get_categories();
                    foreach($categories as $category) {
                     
                      $cat_id = get_cat_ID($category->name);
                        // Get the image ID for the category
                        $image_id = get_term_meta ( $cat_id, 'category-image-id', true );
                        // Echo the image
                ?>
                        <div class="recent-item">
                          <div class="recent-image">
                                <?php echo wp_get_attachment_image ( $image_id, 'large' ); ?>
                            </div>
                            <div class="recent-body">
                                <div class="recent-header">
                                    <h2 class="recent-title">
                                        <?php echo '<a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>'; ?>
                                    </h2>
                                </div>
                                <div class="recent-content">
                                    <?php echo category_description($cat_id);?>
                                </div>
                            </div>
                      </div>
                <?
                    }
                ?>
          </div>
Xem chủ đề cũ hơnVề Đầu TrangXem chủ đề mới hơn
Permissions in this forum:
Bạn không có quyền trả lời bài viết