Cách tạo meta_box, Upload Image, Remove Image, sử dụng wp.media 🌟(ok)

C:\xampp\htdocs\wordpress5\wp-content\themes\twentytwentyone-child\functions.php

<?php
function aw_include_script() {
  if (!did_action('wp_enqueue_media')) {
    wp_enqueue_media();
  }
  wp_enqueue_script('awscript', get_stylesheet_directory_uri() . '/assets/js/awscript.js', array('jquery'), null, false);
}
add_action('admin_enqueue_scripts', 'aw_include_script');
function aw_custom_meta_boxes($post_type, $post) {
  add_meta_box('aw-meta-box', __('Custom Image'), 'render_aw_meta_box', array('post', 'page'), 'normal', 'high');
}
add_action('add_meta_boxes', 'aw_custom_meta_boxes', 10, 2);
function render_aw_meta_box($post) {
  $idimage = get_post_meta($post->ID, 'aw_custom_image', true);
  $image = wp_get_attachment_image_src($idimage);
  ?>
  <div id="updeimg">
      <a href="#" class="aw_upload_image_button button button-secondary">
        <?php if ( $image ) : ?>
          <img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>"/>
          <?php  else: 
            _e('Upload Image');
          ?>
          <?php endif; ?>
      </a>
      <a href="#" class="aw_remove_image_button button button-secondary <?php if ( $image ) {echo "active";} ?>"><?php _e('Remove Image');?></a>
      <input type="hidden" name="aw_custom_image" id="aw_custom_image" value="<?php echo $image; ?>" />
  </div>
  <style type="text/css">
    #updeimg > .aw_remove_image_button {
      display: none;
    }
    #updeimg > .aw_remove_image_button.active {
      display: inline-block;
    }
  </style>
  <?php
}
function aw_save_postdata($post_id) {
  if (array_key_exists('aw_custom_image', $_POST)) {
    update_post_meta($post_id,'aw_custom_image',$_POST['aw_custom_image']);
  }
}
add_action('save_post', 'aw_save_postdata');
?>

C:\xampp\htdocs\wordpress5\wp-content\themes\twentytwentyone-child\assets\js\awscript.js

jQuery(function($) {
  $('body').on('click', '.aw_upload_image_button', function(e) {
    e.preventDefault();
    var button = $(this);
    var aw_uploader = wp.media({
      title: 'Custom image',
      button: {
        text: 'Use this image'
      },
      multiple: false
      }).on('select', function() {
      var attachment = aw_uploader.state().get('selection').first().toJSON();
      $('#aw_custom_image').val(attachment.url);
      button.html('<img src="' + attachment.url + '">').next().show().next().val(attachment.id);
    })
    .open();
  });
  $('body').on('click', '.aw_remove_image_button', function(e) {
    e.preventDefault();
    var button = $(this);
    button.next().val(''); // emptying the hidden field
    button.hide().prev().html('Upload image');
  });
});

Last updated