[FRAMEWORK] Xây dựng page Account Phần 11 (ok)

Like Post, Unlike Post

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\js\account-business.js

jQuery(document).ready(function($) {
  function account_activity_business_load(type) {
    $(".status").removeClass("d-none");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_load_list_' + type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        $(".tab-" + type + " .account-list-item").append(output);
        $(".status").addClass("d-none");
      }
    });
  }
  function account_get_tab_number(type = "activity") {
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'account_activity_get_tab_number',
        type: type,
        token: $("#nonce_token").val()
      },
      success: function(output) {
        if (output != "error") {
          const obj = JSON.parse(output, function(key, value) {
            $(".account-load-btn[data-id='" + key + "'] span").text(value);
          });
        }
      }
    });
  }
  function checkPhoneNumber(element) {
    var flag = false;
    var phone = $(element).val().trim();
    phone = phone.replace('(+84)', '0');
    phone = phone.replace('+84', '0');
    phone = phone.replace('0084', '0');
    phone = phone.replace(/ /g, '');
    if (phone != '') {
      var firstNumber = phone.substring(0, 1);
      if ((firstNumber == '0') && phone.length == 10) {
        if (phone.match(/^\d{10}/)) {
          flag = true;
        }
      }
    }
    return flag;
  }
  // ==
  account_activity_business_load("deal");
  account_get_tab_number();
  // ==
  $('body').on('click', '#change-acc', function(e) {
    const $this = $(this);
    const btnScan = $('#scan-voucher');
    const type = $this.attr('data-type');
    const userId = $this.attr('data-id');
    const tab_active = $(".tab-active").data("tab-id");
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'change_business_activity',
        token: $('#nonce_token').val(),
        type: type,
        id: userId,
      },
      beforeSend: function() {
        $(".account-list-item:not('.news') .col-6").not(".col-addnew").remove();
        $this.find('svg').addClass('spin');
      },
      success: function(response) {
        $(".menu-tab-account .li").not(".active").find("a").addClass("load");
        $this.find('svg').removeClass('spin');
        btnScan.toggle();
        if (type == 'activity') {
          account_get_tab_number("activity");
          $this.attr('data-type', 'business').find('span').text(app.business);
          $(".account-list-item .col-addnew").removeClass("d-none");
          account_activity_business_load(tab_active);
          $(".col-activity-event").remove();
          return;
        }
        $this.data('type', 'activity').find('span').text(app.activity);
        $(".account-list-item .col-addnew").addClass("d-none");
        account_get_tab_number("business");
        $(".menu-tab-account ul li:last-child,.tab-news").removeClass("d-none");
      },
      error: function() {
        $this.find('svg').removeClass('spin');
        alert('Error');
      }
    })
    return false;
  });
  // ==
  var exclude_img = [];
  var input_btn = 0;
  var xp = -1;
  $(document).on("click", ".add-image-btn", function(e) {
    let select = $(this).closest("form");
    input_btn++;
    select.find(".list-input-file").append("<input type='file' name='upload_files[]' id='filenumber" + input_btn + "' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>");
    $("#filenumber" + input_btn).click();
  });
  $(document).on("change", ".upload_files", function(e) {
    let select = $(this).closest("form")
    files = e.target.files;
    filesLength = files.length;
    for (var i = 0; i < filesLength; i++) {
      var f = files[i];
      var res_ext = files[i].name.split(".");
      var img_or_video = res_ext[res_ext.length - 1];
      var fileReader = new FileReader();
      fileReader.name = f.name;
      fileReader.onload = function(e) {
        xp++;
        var file = e.target;
        select.find(".images-box").append("<div class='box preview-image'><div class='images-preview' style='background-image: url(" + e.target.result + ")'><button type='button' data-id='" + xp + "' class='remove-img btn-close' title='Remove'></button></div></div>");
      };
      fileReader.readAsDataURL(f);
    }
  });
  $(document).on("click", ".images-box .remove-img", function() {
    $(this).closest(".box").remove();
    exclude_img.push($(this).attr("data-id"));
  });
  // ==
  var is_busy = false;
  var add_deal_form = "#add-deal-form ";
  $(add_deal_form).submit(function() {
    if (is_busy == true) return;
    is_busy = true;
    var formData = new FormData(document.getElementById("add-deal-form"));
    formData.append('action', 'add_deal');
    formData.append('exclude_img', exclude_img);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: formData,
      success: function(output) {
        is_busy = false;
        if (output == "success") {
          $("#alert-success").modal("show");
          $("#add_deal_form").remove();
        }
      }
    });
    return false;
  });
  $(document).on("click", ".deal.add-favorite", function() {
    if (is_busy == true) return;
    is_busy = true;
    let select = $(this);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'deal_favorite_process',
        id: $(this).data("id"),
        token: $(this).data("token"),
      },
      success: function(output) {
        $(".status").addClass("d-none");
        is_busy = false;
        if (output == "success") {
          select.toggleClass("added");
        }
      }
    })
  });
  $(".account-load-btn").click(function() {
    if ($(this).hasClass("load")) {
      let data_type = $(this).data("id");
      let account_type = $("#change-acc").data("type");
      account_activity_business_load(data_type);
      $(this).removeClass("load");
    }
  });
  $(".save-date-time").click(function() {
    let select = ".add-date-time ";
    let date = $(select + "input[name='date_']").val();
    let time_from = $(select + "input[name='time_from']").val();
    let time_to = $(select + "input[name='time_to']").val();
    if (time_to == null || time_from == null || date == "") {
      $(".date-time-message").html('<div class="alert alert-warning" role="alert">' + app.fill_infor + '</div>')
    } else {
      let date_time = date + ", " + time_from + " - " + time_to;
      $(".event-datetime-text").val(date_time);
      $(".add-date-time").modal("hide");
      $(".step-1").modal("show");
      $(".date-time-message").html("");
    }
  });
  var add_event_class_arr = ["event-datetime-text", "address-input", "description", "title", "phone"];
  $.each(add_event_class_arr, function(index, value) {
    $("#add-event-form ." + value).click(function() {
      $("#add-event-form  .step-1-message").html('');
    });
  });
  $(".add-event-btn").click(function() {
    $.each(add_event_class_arr, function(index, value) {
      if ($("#add-event-form ." + value).val() == "") {
        $("#add-event-form  .step-1-message").html('<div class="alert alert-warning" role="alert">' + app.fill_infor + '</div>');
        return;
      }
      if (!checkPhoneNumber("#add-event-form [name='phone']")) {
        $("#add-event-form .step-1-message").html('<div class="alert alert-warning" role="alert">' + app.phone_valid + '</div>');
        return;
      }
    });
  });
  $("#add-event-form").submit(function() {
    if (is_busy == true) return;
    is_busy = true;
    var formData = new FormData(document.getElementById("add-event-form"));
    formData.append('action', 'add_event');
    formData.append('exclude_img', exclude_img);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: formData,
      success: function(output) {
        is_busy = false;
        if (output == "success") {
          $("#add-market-success").modal("show");
          $("#add_event_form").remove();
        }
      }
    });
    return false;
  });
  $("#add-post-form").submit(function() {
    if (is_busy == true) return;
    is_busy = true;
    var formData = new FormData(document.getElementById("add-post-form"));
    formData.append('action', 'add_post');
    formData.append('exclude_img', exclude_img);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: formData,
      success: function(output) {
        is_busy = false;
        if (output == "success") {
          $("#add-market-success").modal("show");
          $("#add_event_form").remove();
        }
      }
    });
    return false;
  });
  $(".save-address").click(function() {
    let city_val = $(".province-select").val();
    let city_text = $(".province-select option:selected").text();
    let district_val = $(".district-select").val();
    let district_text = $(".district-select option:selected").text();
    let ward_val = $(".ward-select").val();
    let ward_text = $(".ward-select option:selected").text();
    let street_text = $(".street").val();
    if (city_val == null || district_val == null || ward_val == null || street_text == "") {
      $(".address-message").html('<div class="alert alert-warning" role="alert">' + app.fill_infor + '</div>')
    } else {
      let address = street_text + ", " + ward_text + ", " + district_text + ", " + city_text;
      $(".address-input").val(address);
      $(".add-adress").modal("hide");
      $(".step-1").modal("show");
      $(".address-message").html("");
    }
  });
  $(document).on("click", ".news.add-favorite", function() {
    if (is_busy == true) return;
    is_busy = true;
    let select = $(this);
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      dataType: "text",
      data: {
        action: 'news_favorite_process',
        post_id: $(this).data("id"),
        token: $("#nonce_token").val()
      },
      success: function(output) {
        if (output == "success") {
          select.toggleClass("added");
        }
        is_busy = false;
      }
    })
  });
});

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\ajax\news.php

<?php
add_action('wp_ajax_news_favorite_process', 'news_favorite_process');
function news_favorite_process() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) or !wp_verify_nonce($_POST['token'], AT_NONCE_KEY . 'ajax-nonce' . $current_user_id)) {
    die("error 1");
  }
  $meta_key = "news_favorite";
  if (!empty($_POST["post_id"]) && is_numeric($_POST["post_id"]) && get_post_type($_POST["post_id"]) == "post") {
    $post_id = (int) $_POST["post_id"];
  } else {
    die("error 2");
  }
  ;
  $c_list_favorite_arr = get_user_meta($current_user_id, $meta_key, true);
  if (!empty($c_list_favorite_arr) && is_array($c_list_favorite_arr)) {
    if (in_array($post_id, $c_list_favorite_arr)) {
      if (($key = array_search($post_id, $c_list_favorite_arr)) !== false) {
        unset($c_list_favorite_arr[$key]);
      }
    } else {
      $c_list_favorite_arr[] = $post_id;
    }
    $arr_to_update = $c_list_favorite_arr;
  } else {
    $arr_to_update = [$post_id];
  }
  $result = update_user_meta($current_user_id, $meta_key, json_encode($arr_to_update));
  if ($result != false) {
    echo "success";
  }
  die();
}
add_action('wp_ajax_add_post', 'add_post');
function add_post() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) or !wp_verify_nonce($_POST['token'], BJ_NONCE_KEY . "addpost" . $current_user_id)) {
    die("error 1");
  }
  if (!empty($_POST["title"])) {
    $title = $_POST["title"];
  } else {
    die("error 2,1");
  }
  if (!empty($_POST["description"])) {
    $description = $_POST["description"];
  } else {
    die("error 3");
  }
  $my_post = array(
    'post_title'    => $title,
    'post_content'  => $description,
    'post_status'   => 'publish',
    'post_author'   => $current_user_id,
    'post_category' => array(1),
  );
  wp_insert_post($my_post);
  wp_die();
}
?>

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\ajax\account.php

<?php
/**
 * App Update Info
 */
add_action('wp_ajax_app_update_info', 'app_update_info');
function app_update_info() {
  check_ajax_referer(AT_NONCE_KEY . 'update-info', 'update-info-token');
  $status   = false;
  $message  = '';
  $username = sanitize_text_field($_POST['username']);
  $phone    = sanitize_text_field($_POST['phone']);
  $email    = sanitize_text_field($_POST['email']);
  $language = sanitize_text_field($_POST['language']);
  $province = intval($_POST['province']);
  $district = intval($_POST['district']);
  $ward     = intval($_POST['ward']);
  $street   = sanitize_text_field($_POST['street']);
  global $current_user;
  $current_email            = $current_user->user_email;
  $current_user_id          = $current_user->ID;
  $data_user_for_update_arr = array(
    'ID'           => $current_user_id,
    'display_name' => $username,
  );
  $province_address = array(
    'province' => $province,
    'district' => $district,
    'ward'     => $ward,
    'street'   => $street,
  );
  $province_address = json_encode($province_address, JSON_UNESCAPED_UNICODE);
  if ($current_email != $email) {
    if (email_exists($email)) {
      $status  = true;
      $message = __("Email already exists", "umm");
    } elseif (!is_email($email)) {
      $status  = true;
      $message = __("Invalid email", "umm");
    } else {
      $data_user_for_update_arr["user_email"] = $email;
    }
  }
  if (!$status) {
    wp_update_user($data_user_for_update_arr);
    update_user_meta($current_user_id, 'user_phone', $phone);
    update_user_meta($current_user_id, 'language', $language);
    update_user_meta($current_user_id, "province_address", $province_address);
  }
  if (isset($_FILES["image-avarta"]) && !empty($_FILES['image-avarta']['name'])) {
    $result_upload = upload_image($_FILES["image-avarta"]);
    if ($result_upload['status'] == 'success') {
      $id_avatar_curr = get_user_meta($current_user_id, 'id_img_avatar', true);
      if ($id_avatar_curr) {
        delete_img_by_id($id_avatar_curr);
      }
      update_user_meta($current_user_id, 'id_img_avatar', $result_upload['content']);
    } else {
      $message = __("upload error ", "umm");
      $status  = true;
    }
  }
  echo json_encode(array(
    'status'  => $status,
    'message' => $message)
  );
  die();
}
/**
 * Add Follow
 */
add_action('wp_ajax_app_add_follow', 'app_add_follow');
function app_add_follow() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) || !wp_verify_nonce($_POST['token'], AT_NONCE_KEY . 'ajax-nonce' . $current_user_id)) {
    die("error verify");
  }
  $user_id          = intval($_POST["id"]);
  $list_user_follow = get_user_meta($current_user_id, 'list_user_follow', true);
  if ($list_user_follow) {
    $list_user_follow_arr = json_decode($list_user_follow, true);
    if (is_array($list_user_follow_arr)) {
      $list_user_follow_arr[] = $user_id;
    }
  } else {
    $list_user_follow_arr = array($user_id);
  }
  $list_user_follow_arr = array_unique($list_user_follow_arr);
  $result               = update_user_meta($current_user_id, 'list_user_follow', json_encode($list_user_follow_arr));
  if ($result) {
    global $bj_controller;
    $model = $bj_controller->Model("notification");
    $id    = $model->create_notification(
      array(
        "from"    => $current_user_id,
        "to"      => $user_id,
        "type"    => "has_follow",
        "content" => '',
      )
    );
    if ($id) {
      update_total_notify_user($user_id);
    }
    echo true;
  }
  die();
}
/**
 * Un Follow
 */
add_action('wp_ajax_app_un_follow', 'app_un_follow');
function app_un_follow() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) || !wp_verify_nonce($_POST['token'], AT_NONCE_KEY . 'ajax-nonce' . $current_user_id)) {
    die("error verify");
  }
  $user_id              = intval($_POST["id"]);
  $list_user_follow_arr = list_user_follow();
  if (($key = array_search($user_id, $list_user_follow_arr)) !== false) {
    unset($list_user_follow_arr[$key]);
    global $bj_controller;
    $model  = $bj_controller->Model("notification");
    $result = $model->del_notification_exact(
      array(
        "from"    => $current_user_id,
        "to"      => $user_id,
        "type"    => "has_follow",
        "content" => '',
      )
    );
  }
  $result = update_user_meta($current_user_id, 'list_user_follow', json_encode($list_user_follow_arr));
  if ($result) {
    echo true;
  }
  die();
}
/**
 * Change business and activity
 */
add_action('wp_ajax_change_business_activity', 'change_business_activity');
function change_business_activity() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) || !wp_verify_nonce($_POST['token'], AT_NONCE_KEY . 'ajax-nonce' . $current_user_id)) {
    die();
  }
  $type    = $_POST['type'];
  $user_id = intval($_POST['id']);
  if ($type == 'business') {
    echo "data activity";
    die();
  }
  // activity
  echo "data business";
  die();
}

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\models\post.php

<?php
class BJ_post_Model {
  private $table_post = 'posts';
  public function get_list_post_id_saved($user_id) {
    global $wpdb;
    $arr    = [];
    $table  = $wpdb->prefix . "usermeta";
    $result = $wpdb->get_results($wpdb->prepare(" SELECT user_id FROM  {$table} WHERE news_favorite IN ('{$array}')", $user_id), ARRAY_A);
    if (!empty($result)) {
      foreach ($result as $value) {
        $arr[] = $value["ID"];
      }
    }
    return $arr;
  }
  public function get_list_post_saved($user_id) {
    global $wpdb;
    $table  = $wpdb->prefix . "usermeta";
    $result = $wpdb->get_results("SELECT * FROM  {$table} WHERE user_id = $user_id", ARRAY_A);
    return $result;
  }
  public function get_post_user_status($post_id, $user_id) {
    global $wpdb;
    $table  = $wpdb->prefix . "usermeta";
    $result = $wpdb->get_results($wpdb->prepare(" SELECT type FROM  {$table} WHERE post_id = %d AND user_id = %d", $post_id, $user_id), ARRAY_A);
    if (!empty($result)) {
      return $result[0]["type"];
    }
  }
  public function add_post($data,$format){
    global $wpdb;
    $table = $wpdb->prefix.$this->table_post;
    $wpdb->insert($table,$data,$format);
    return $wpdb->insert_id;
  }
} //end class

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\views\post\item.php

<?php  
  $arrvs = json_decode($args['meta_value'], TRUE);
  if($args['meta_key'] == 'news_favorite' && !empty($arrvs)){
    foreach ($arrvs as $post_id) {
      $link = get_the_permalink($post_id)."?appt=N";
?>
<div class="col-6 ">
  <a href="<?php echo $link ?>">
      <?php echo get_the_post_thumbnail($post_id,"medium",array("class"=>"w-100")) ?>
    </a>
  <div class="bottom">
    <a class="title" href="<?php echo $link ?>"><?php echo get_the_title($post_id); ?></a>
    <div class="text-right">
      <button class="news add-favorite" data-id="<?php echo $post_id; ?>">
        <svg width="15" height="27" viewBox="0 0 20 27" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M19 26L10 19.0556L1 26V3.77778C1 3.04107 1.27092 2.33453 1.75315 1.81359C2.23539 1.29266 2.88944 1 3.57143 1H16.4286C17.1106 1 17.7646 1.29266 18.2468 1.81359C18.7291 2.33453 19 3.04107 19 3.77778V26Z" fill="#686868" stroke="#686868" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
        </svg>
      </button>
    </div>
  </div>
</div>
<?php }} ?>

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\inc\functions\function-setup.php

<?php
add_filter('use_block_editor_for_post', '__return_false');
if (!is_super_admin()) {
  /* Disable Admin Bar */
  add_filter('show_admin_bar', '__return_false');
}
function at_umm_setup() {
  add_theme_support('title-tag');
  /* load theme languages */
  //load_theme_textdomain('umm', get_template_directory() . '/languages');
  /* Add support for post thumbnails */
  add_theme_support('post-thumbnails');
  /* Add support for HTML5 */
  add_theme_support('html5', array(
    'search-form',
    'comment-form',
    'comment-list',
    'gallery',
    'caption',
    'widgets',
  ));
  /*  Enable support for Post Formats */
  add_theme_support( 'post-formats', array( 'video' ) );
}
add_action('after_setup_theme', 'at_umm_setup');
/**
 * Setup Styles and Scripts
 */
function at_umm_scripts() {
  wp_dequeue_style('wp-block-library'); // remove block-library/style.min.css
  // add Styles.
  wp_enqueue_style('umm-main-css', THEME_URL . 'css/app.min.css', array(), THEME_VERSION, 'all');
  if(is_page("account") || get_post_type() == 'post'){
    wp_enqueue_script('business-script', THEME_URL. 'js/account-business.js', array(),"36", true);
  };
  // add Scripts
  wp_enqueue_script('umm-main-js', THEME_URL . 'js/frontend.js', array('jquery'), THEME_VERSION, true);
  // Add variables to scripts.
  $php_var_array = array(
    'ajaxUrl'        => admin_url('admin-ajax.php'),
    'siteUrl'        => home_url(),
    'follow'         => __('Follow', 'umm'),
    'unfollow'       => __('Unfollow', 'umm'),
    'appoint_admin'  => __('Appoint as admin', 'umm'),
    'appoint_member' => __('Appoint as member ', 'umm'),
    'admin'          => __('admin', 'umm'),
    'member'         => __('member', 'umm'),
    'mute_on'        => __('Turn on notification', 'umm'),
    'mute_off'       => __('Mute notification', 'umm'),
    'business'       => __('Business', 'umm'),
    'activity'       => __('Activity', 'umm'),
    'sent'           => __('Sent', 'umm'),
  );
  wp_localize_script('umm-main-js', 'app', $php_var_array);
}
add_action('wp_enqueue_scripts', 'at_umm_scripts', 100);
/**
 * admin stylesheet
 */
add_action('admin_enqueue_scripts', 'adimin_enqueue_js');
function adimin_enqueue_js() {
  if (!did_action('wp_enqueue_media')) {
    wp_enqueue_media();
  }
  wp_register_script('admin_js', THEME_URL . '/js/backend.js', array('jquery'), 1.0);
  wp_enqueue_script('admin_js');
  wp_enqueue_style('admin-css', THEME_URL . '/css/admin-styles.css', false, 1.0);
}
/**
 * Remove jquery-migrate
 */
function dequeue_jquery_migrate($scripts) {
  if (!is_admin() && !empty($scripts->registered['jquery'])) {
    $scripts->registered['jquery']->deps = array_diff(
      $scripts->registered['jquery']->deps,
      ['jquery-migrate']
    );
  }
}
// add_action('wp_default_scripts', 'dequeue_jquery_migrate');
/**
 * Remove wp-embed
 */
function my_deregister_scripts() {
  wp_dequeue_script('wp-embed');
}
// add_action('wp_footer', 'my_deregister_scripts');
/**
 * Disable the emoji's
 */
function disable_emojis() {
  remove_action('wp_head', 'print_emoji_detection_script', 7);
  remove_action('admin_print_scripts', 'print_emoji_detection_script');
  remove_action('wp_print_styles', 'print_emoji_styles');
  remove_action('admin_print_styles', 'print_emoji_styles');
  remove_filter('the_content_feed', 'wp_staticize_emoji');
  remove_filter('comment_text_rss', 'wp_staticize_emoji');
  remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
  // Remove from TinyMCE
  add_filter('tiny_mce_plugins', 'disable_emojis_tinymce');
}
add_action('init', 'disable_emojis');
/**
 * Filter out the tinymce emoji plugin.
 */
function disable_emojis_tinymce($plugins) {
  if (is_array($plugins)) {
    return array_diff($plugins, array('wpemoji'));
  } else {
    return array();
  }
}
/**
 *
 * Set load languages
 *
 */
add_filter('locale', 'at_switch_language');
function at_switch_language($locale) {
  //return 'en_US';
  if (!is_admin()) {
    if (isset($_COOKIE['app_language'])) {
      return $_COOKIE['app_language'];
    }
    return 'en_US';
  }
}

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\comments.php

<?php get_header() ?>
<?php
$author_id            = $post->post_author;
$current_user_id      = get_current_user_id();
$list_images_post_arr = [];
?>
<?php if ( get_post_meta( get_the_ID(), 'img_single_community', true ) ) : ?>       
  <?php $list_images_post_arr = json_decode( get_post_meta(get_the_ID(),"img_single_community",true),true );?>    
<?php endif; ?>
<div class="box-deal box-post">
	<?php if ( has_post_thumbnail() ) { ?>
    <figure class="featured-media">
      <?php the_post_thumbnail(); ?>
    </figure>
  <?php } ?>
  <div class="sigle__content">
    <?php the_content(); ?>
  </div>
  <div class="box-image">
  	<?php 
      if(isset($list_images_post_arr)){
        $cont_images = count($list_images_post_arr);
        if( $cont_images == 1){
          echo '<a href="'.get_image_url_by_id(reset($list_images_post_arr)).'"><img class="thumb" src="'.get_image_url_by_id(reset($list_images_post_arr)).'" /></a>';
        }else{
          echo '<div class="grid grid-cols-2 gap-2 p-2">';
	          foreach ($list_images_post_arr as $key => $value) {
	            echo '<a href="'.get_image_url_by_id($value).'"><img class="thumb" src="'.get_image_url_by_id($value, '200x200').'" /></a>';
	          }
          echo '</div>';
        }
      }
    ?>  
  </div>
  <?php 
    $list_like_post_arr = !empty(get_post_meta(get_the_ID(),"list_user_like",true)) ? json_decode( get_post_meta(get_the_ID(),"list_user_like",true),true ) : [];
    if (!in_array(get_current_user_id(), $list_like_post_arr) ){
      $class = "like";
    }else{
      $class = "dislike";
    }
    $count_like = count($list_like_post_arr);
  ?>
  <div class="boxaction" >
  	<div class="action">
  		<a data-id = "<?php echo get_the_ID(); ?>" data-author="<?php echo $author_id=$post->post_author; ?>" data-token = "<?php echo wp_create_nonce( get_current_user_id()) ?>" href="#" class="<?php echo $class;?> action__like news add-favorite">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100"><path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" /></svg>
        <div class="action__button"><?php _e("Like","dragon") ?> <span class="count_like"> <?php echo $count_like; ?> </span></div>
      </a>
      <div class="action__comment">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
            <path fill-rule="evenodd" d="M18 5v8a2 2 0 01-2 2h-5l-5 4v-4H4a2 2 0 01-2-2V5a2 2 0 012-2h12a2 2 0 012 2zM7 8H5v2h2V8zm2 0h2v2H9V8zm6 0h-2v2h2V8z" clip-rule="evenodd"></path>
          </svg>
        <div class="action__button"><?php _e("Comment","dragon") ?> <span class="count_cm"> <?php echo get_comments_number(get_the_ID()); ?> </span> </div>
      </div>
    </div>
    <div class="list">
    	<?php 
        $args = array(
          'post_id' => get_the_ID(),
          'status' => 'approve',
          'hierarchical' => true,
          'order'     => 'ASC'
        );
        $comments = get_comments( $args );  
      ?>
      <?php foreach ($comments as $key => $comment): ?>
      	<?php if($comment->comment_parent == 0): ?>
      		<div class="parents <?php echo 'comment_id_'.$comment->comment_ID; ?>">
    				<a class="parents__avatar" href="<?php echo site_url('/') ?>account?id=<?php echo $comment->user_id; ?>">
              <img src="<?php echo get_avatar_url($comment->user_id);?>" width="40" height="40" class = "avatar avatar-40 photo" alt="">
            </a>
      			<div class="parents__content">
      				<div class="parents__author">
                <span class="author"><a href="<?php echo site_url('/') ?>account?id=<?php echo $comment->user_id; ?>"><?php echo $comment->comment_author; ?></a></span>
                <p class="parents__coment"><?php echo $comment->comment_content; ?></p>
              </div>
              <div class="parents__reply">
                <a href="#" class="replay-comment" author-name ="<?php echo $comment->comment_author; ?>" comment-id="<?php echo $comment->comment_ID; ?>"><?php _e("Reply","dragon") ?> </a>
                <?php  if ($current_user_id == $comment->user_id ){ ?>
                  <a href="#" class="delete-comment" data-hierar="0" comment-id="<?php echo $comment->comment_ID; ?>"> <?php _e("Delete","dragon") ?> </a>
                <?php } ?>
                <span><?php  echo human_time_diff(strtotime($comment->comment_date),current_time( 'U' ))." ".__("ago","dragon"); ?></span>
              </div>
      			</div>
      			<?php 
	            $args = array(
	              'parent' => $comment->comment_ID,
	              'status' => 'approve',
	              'hierarchical' => true,
	              'order'     => 'ASC'
	             );
	            $child_comments = get_comments($args);
            ?>
           	<?php foreach ($child_comments as $keyc => $child_comment): ?>
           	<div class="childs">
           			<a class="childs__avatar" href="<?php echo site_url('/') ?>account?id=<?php echo $child_comment->user_id; ?>">
                  <img src="<?php echo get_avatar_url($child_comment->user_id);?>" class = "avatar avatar-40 photo" width="30" height="30" alt="">
                </a>
                <div class="childs__content">
                	<div class="parents__author">
		                <span class="author"><a href="<?php echo site_url('/') ?>account?id=<?php echo $comment->user_id; ?>"><?php echo $child_comment->comment_author; ?></a></span>
		                <p class="parents__coment"><?php echo $child_comment->comment_content; ?></p>
		              </div>
		              <div class="parents__reply">
		                <a href="#" class="replay-comment" author-name ="<?php echo $child_comment->comment_author; ?>" comment-id="<?php echo $child_comment->comment_ID; ?>"><?php _e("Reply","dragon") ?> </a>
		                <?php  if ($current_user_id == $child_comment->user_id ){ ?>
		                  <a href="#" class="delete-comment" data-hierar="0" comment-id="<?php echo $comment->comment_ID; ?>"> <?php _e("Delete","dragon") ?> </a>
		                <?php } ?>
		                <span><?php  echo human_time_diff(strtotime($comment->comment_date),current_time( 'U' ))." ".__("ago","dragon"); ?></span>
		              </div>
                </div>
           	</div>
           	<?php endforeach ?>
      		</div>
      	<?php endif ?>
      <?php endforeach ?>
    </div>
  </div>
  <div class="boxcomment">
    <input name="add_comment" data-postid = "<?php echo get_the_ID(); ?>" data-id_comment_parent="0" placeholder="<?php _e("Add your Comment..","dragon") ?>" value="" required data-token = "<?php echo wp_create_nonce(get_current_user_id().'add_comment'); ?>" class="add_comment">
  </div>
</div>
<?php get_footer() ?>

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\ajax\business.php

<?php
add_action('wp_ajax_account_activity_load_list_deal', 'account_activity_load_list_deal');
function account_activity_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("business");
  $list_deal = $model->activity_load_deal_id(5);
  if(!empty($list_deal)){
    $deal_model = $bj_controller->Model("deal");
    foreach ($list_deal as  $value) {
      $deal_detail = $deal_model->get_deal_detail($value["deal_id"]);
      echo '<div class="col-6">';
        get_template_part("framework/views/deal/item","",$deal_detail);
      echo '</div>';
    }
  }else{
    echo '<p class="p-3">'.__("No data","umm").'</p>';
  }
  wp_die();
}
add_action('wp_ajax_account_activity_get_tab_number', 'account_activity_get_tab_number');
function account_activity_get_tab_number() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  if(!isset($_POST["type"]) or !in_array($_POST["type"],["activity","business"])) die("error");
  global $bj_controller, $wpdb;
  $return = array(
    "deal" => 0,
    "event" => 0,
    "market" => 0,
    "business" => 0,
  );
  if($_POST["type"] == "activity"){
    $list_deal = $bj_controller->Model("business")->activity_load_deal_id(10000);
    if(!empty($list_deal)) $return["deal"] = count($list_deal);
    $list_event = $bj_controller->Model("event")->get_list_event_saved($current_user_id);
    if(!empty($list_event)) $return["event"] = count($list_event);
  }else{
    $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
    if(!empty($list_business_arr)) {
      $arr = [];
      foreach ($list_business_arr as $value) {
        $arr[] = $value["id"];
      }
      $table = $wpdb->prefix."bj_business_deal";
      $business_id_arr = implode("','",$arr);
      $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
      if(!empty($list_deal)) $return["deal"] = count($list_deal);
    };
  }
  die(json_encode($return));
}
add_action('wp_ajax_account_business_load_list_deal', 'account_business_load_list_deal');
function account_business_load_list_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  global $wpdb;
  $list_business_arr = $bj_controller->Model("business")->get_list_business_by_user_id($current_user_id);
  if(!empty($list_business_arr)) {
    $arr = [];
    foreach ($list_business_arr as $value) {
      $arr[] = $value["id"];
    }
    $table = $wpdb->prefix."bj_business_deal";
    $business_id_arr = implode("','",$arr);
    $list_deal = $wpdb->get_results ( " SELECT * FROM  {$table} WHERE business_id IN ('{$business_id_arr}') ORDER BY id DESC" ,ARRAY_A);
    if(!empty($list_deal)){
      $deal_model = $bj_controller->Model("deal");
      foreach ($list_deal as  $value) {
        $deal_detail = $deal_model->get_deal_detail($value["id"]);
        $deal_detail["account"] = true;
        echo '<div class="col-6">';
        $bj_controller->View("item", $deal_detail, "deal"); 
        echo '</div>';
      }
    }else{
      echo '<p class="p-3">'.__("No data","umm").'</p>';
    }
  };
  wp_die();
}
add_action('wp_ajax_add_deal', 'add_deal');
function add_deal() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'], BJ_NONCE_KEY.'adddeal'.$current_user_id ) ) {
    wp_die("error1"); 
  } 
  if(!empty($_POST['title']) && strlen($_POST["title"]) < 250 ){
    $title = strip_tags($_POST["title"]);}else{
    wp_die("error2");
  }
  if(!empty($_POST['description'])){
    $description = strip_tags($_POST["description"]);
  }else{
    wp_die("error3");
  }
  if(!empty($_POST['date_from'])){
    $date_from = strip_tags($_POST["date_from"]);
  }else{
    wp_die("error4");
  }
  if(!empty($_POST['date_to'])){
    $date_to = strip_tags($_POST["date_to"]);
  }else{
    wp_die("error5");
  }
  if(!empty($_POST['quantity']) && is_numeric($_POST["quantity"]) && $_POST['quantity'] < 9999999){
    $quantity = $_POST["quantity"];
  }else{
    wp_die("error6");
  }
  global $bj_controller;
  $model = $bj_controller -> Model("directory");
  if(!empty($_POST['business_id']) && is_numeric($_POST["business_id"]) && !empty($model->get_business_detail($_POST["business_id"]))){
    $business_id = $_POST["business_id"];
  }else{
      wp_die("error7");
  }
  $file_arr = $list_image_uploaded = [];
  if(!empty($_FILES["upload_files"])){    
    foreach ($_FILES["upload_files"]["name"] as $key => $value) {
      $file_arr[] = array(
        "name" => $_FILES["upload_files"]["name"][$key],
        "type" => $_FILES["upload_files"]["type"][$key],
        "tmp_name" => $_FILES["upload_files"]["tmp_name"][$key],
        "error" => $_FILES["upload_files"]["error"][$key],
        "size" => $_FILES["upload_files"]["size"][$key]
      );
    }
  }
  if(!empty($img_exclude)){
      foreach ($img_exclude as $key) {
        unset($file_arr[$key]);
      }
    }
    $district = "";
    $business_detai = $bj_controller->Model("business")->get_business_detail($business_id);
    if(!empty($business_detai)) $district = $business_detai["district"];
    $data_add = array(
    "business_id" => $business_id,
    "title" => $title,
    "description" => $description,
    "date_from" => $date_from,
    "date_to" => $date_to,
    "quantity" => $quantity,
    "district" => $district,
  );
  $data_format = array("%d","%s","%s","%s","%s","%d","%s");
  if(!empty($file_arr)){
    foreach ($file_arr as $file) {
      $upload_result = market_upload_image($file);
      if($upload_result["status"] == "success"){
        $list_image_uploaded[] = $upload_result["content"];
      }
    }
  }
  if(!empty($list_image_uploaded)){
    $data_add["images"] = json_encode($list_image_uploaded);
    $data_format[] = "%s";
  }
  $model = $bj_controller->Model("deal");
  $deal_id = $model->add_deal($data_add,$data_format);  
  echo $deal_id > 0 ? "success" : "error";
  wp_die();
}
add_action('wp_ajax_account_activity_load_list_event', 'account_activity_load_list_event');
function account_activity_load_list_event() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("event");
  echo '<div class="col-12 col-activity-event">';
  foreach (["going","maybe"] as $type) {
    $list_event = $model->get_list_event_saved($current_user_id,$type);
    echo '<div class="row '.$type.'">';
    echo '<div class="col-12 col-title"><h5>'.$type.'</h5></div>';
    if(!empty($list_event)){
      foreach ($list_event as  $data) {
        $data["type"] = $type;
        echo '<div class="col-6">';
          $bj_controller->View("item", $data, "event"); 
        echo '</div>';
      }
    }else{
      echo '<p class="col-6">'.__("No data","umm").'</p>';
    }
    echo '</div>';
  }
  echo '</div>';
  wp_die();
}

add_action('wp_ajax_account_activity_load_list_news', 'account_activity_load_list_news');
function account_activity_load_list_news() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],AT_NONCE_KEY.'ajax-nonce'.$current_user_id ) ) die("error"); 
  global $bj_controller;
  $model = $bj_controller->Model("post");
    $list_post = $model->get_list_post_saved($current_user_id);
    if(!empty($list_post)){
      foreach ($list_post as  $data) {
          $bj_controller->View("item", $data, "post"); 
      }
    }else{
      echo '<p class="col-6">'.__("No data","umm").'</p>';
    }
  wp_die();
}
add_action('wp_ajax_add_event', 'add_event');
function add_event() {
  $current_user_id = get_current_user_id();
  if( !isset( $_POST['token']) or !wp_verify_nonce($_POST['token'],BJ_NONCE_KEY.'addevent'.$current_user_id ) ) die("error"); 
  if(!empty($_POST['title']) && strlen($_POST["title"]) < 250 ){$title = strip_tags($_POST["title"]);}else{die("error");}
  if(!empty($_POST['description'])){$description = strip_tags($_POST["description"]);}else{die("error");}
  if(!empty($_POST['date_'])){$date_ = strip_tags($_POST["date_"]);}else{die("error");}
  if(!empty($_POST['time_from'])){$time_from = strip_tags($_POST["time_from"]);}else{die("error");}
  if(!empty($_POST['time_to'])){$time_to = strip_tags($_POST["time_to"]);}else{die("error");}
  if(!empty($_POST['province']) and is_numeric($_POST["province"])){$province = strip_tags($_POST["province"]);}else{die("error7");}
  if(!empty($_POST['district']) and is_numeric($_POST["district"])){
    $district = strip_tags($_POST["district"]);
  }
  else{
    wp_die("error8");
  }
  if(!empty($_POST['ward']) and is_numeric($_POST["ward"])){$ward = strip_tags($_POST["ward"]);}else{die("error9");}
  if(!empty($_POST['street'])){$street = strip_tags($_POST["street"]);}else{die("street");}
  $phone = isset($_POST["phone"]) ? strip_tags(str_replace(' ', '', $_POST["phone"])) : 0;
  global $bj_controller;
  $file_arr = $list_image_uploaded = [];
  if(!empty($_FILES["upload_files"])){    
    foreach ($_FILES["upload_files"]["name"] as $key => $value) {
      $file_arr[] = array(
        "name" => $_FILES["upload_files"]["name"][$key],
        "type" => $_FILES["upload_files"]["type"][$key],
        "tmp_name" => $_FILES["upload_files"]["tmp_name"][$key],
        "error" => $_FILES["upload_files"]["error"][$key],
        "size" => $_FILES["upload_files"]["size"][$key]
      );
    }
  }
  if(!empty($img_exclude)){
      foreach ($img_exclude as $key) {
        unset($file_arr[$key]);
      }
    }
    $data_add = array(
    "user_id" => $current_user_id,
    "title" => $title,
    "description" => $description,
    "phone" => $phone,
    "date_" => $date_,
    "time_from" => $time_from,
    "time_to" => $time_to,
    "province" => $province,
    "district" => $district,
    "ward" => $ward,
    "street" => $street,
  );
  $data_format = array("%d","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s");
  if(!empty($file_arr)){
    foreach ($file_arr as $file) {
      $upload_result = market_upload_image($file);
      if($upload_result["status"] == "success"){
        $list_image_uploaded[] = $upload_result["content"];
      }
    }
  }
  if(!empty($list_image_uploaded)){
    $data_add["images"] = json_encode($list_image_uploaded);
    $data_format[] = "%s";
  }
  $model = $bj_controller->Model("event");
  $deal_id = $model->add_event($data_add,$data_format); 
  echo $deal_id > 0 ? "success" : "error";
  die();
}

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\views\post\add-post.php

<?php  
  $current_user_id = get_current_user_id();
?>
<!-- Modal -->
<form id="add-post-form" class="step-by-step event-form" action="javascript:void(0)">
    <div class="modal animate step-1" style="display: block;">
        <div class="modal-dialog modal-fullscreen a-fadeLeft">
            <div class="modal-content">
                <div class="modal-header">
                    <a href="?appt=X" class="btn-close"></a>
                    <h5 class="modal-title"><?php _e("Add Post","umm") ?></h5>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php _e("Title","umm") ?></label>
                        <input type="text" name="title" class="form-control title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php _e("Description","umm") ?></label>
                        <textarea class="form-control description" name="description" required></textarea>
                    </div>
                    <button type="submit" class="btn btn-bottom add-post-btn"><?php _e("Submit","umm") ?></button>
                </div>
            </div>
        </div>
    </div>
    <input type="hidden" name="token" value="<?php echo wp_create_nonce(BJ_NONCE_KEY."addpost".$current_user_id) ?>">
    <div class="list-input-file d-none"></div>
</form>
<div class="modal fade alert-modal confirm-modal" id="alert-success" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-fullscreen">
    <div class="modal-content">
      <div class="modal-header">
        <a href="?appt=X&data=tab_event" class="btn-close"></a>
      </div>
      <div class="modal-body">
        <p><?php _e("Create new successfully","umm") ?></p>
        <div class="group-button">
            <a href="?appt=X&data=tab_event" class="btn btn-confirm"><?php _e("OK","umm") ?></a>
        </div>
      </div>
    </div>
  </div>
</div>

C:\xampp\htdocs\reset4\wp-content\themes\addframwork\framework\controllers\Account.php

<?php
class BJ_Account_Controller extends Pv_Controller {
  function __construct() {
    if (isset($_GET['action'])):
      switch ($_GET['action']) {
      case "edit-info":
        $this->update_info();
        break;
      case "followers":
        $this->followers();
        break;
      case "following":
        $this->following();
        break;
      case "add-deal":
        $this->adddeal();
      break;
      case "add-event":
        $this->addevent();
      break;
      case "add-post":
        $this->addposts();
      break;
      default:
        $this->index();
      } else :
      $this->index();
    endif;
  }
  private function get_user_id() {
    if (isset($_GET["id"]) && is_user_exist(strip_tags($_GET["id"]))) {
      return $_GET["id"];
    } else {
      return get_current_user_id();
    }
  }
  public function index() {
    $data                         = array();
    $user_id                      = $this->get_user_id();
    $user_obj                     = get_userdata($user_id);
    $data['id']                   = $user_id;
    $data['display_name']         = $user_obj->display_name;
    $data['date_registered']      = date_i18n(__('jS F Y', 'umm'), strtotime($user_obj->user_registered));
    $data['avatar']               = get_url_avatar($user_id);
    $data['province_address_arr'] = atw_load_province_address($user_id);
    $this->load()->View("account", $data, "account");
  }
  public function update_info() {
    $data = array();
    $this->load()->View("update-info", $data, "account");
  }
  public function followers() {
    $current_user_id       = $this->get_user_id();
    $data                  = array();
    $data['list_follower'] = get_list_follower($current_user_id);
    $this->load()->View("followers", $data, "account");
  }
  public function following() {
    $user_id             = $this->get_user_id();
    $data                = array();
    $data['list_follow'] = list_user_follow($user_id);
    $this->load()->View("following", $data, "account");
  }
  public function adddeal() {
    $this->load()->View("add-deal", '', "deal"); 
  }
  public function addevent() {
    $this->load()->View("add-event", '', "event"); 
  }
  public function addposts() {
    $this->load()->View("add-post", '', "post"); 
  }
}
function render_province_option($default = ""){  
  $json = file_get_contents(get_stylesheet_directory()."/json/tinh_tp.json");
  $tinh_thanh = json_decode($json,true);
  foreach ($tinh_thanh as $key => $value) {
    if($key == $default){$select = "selected";}else{$select = "";}
    echo "<option ".$select." value='".$key."'>".$value["name"]."</option>";
  }
}
function render_xa_phuong_option($quan_huyen,$default=""){
  $default = intval($default);
  $json = file_get_contents(get_stylesheet_directory()."/json/xa-phuong/".$quan_huyen.".json");
  $xa_phuong = json_decode($json,true);
  foreach ($xa_phuong as $key => $value) {
      if($key == $default){$select = "selected";}else{$select = "";}
      echo "<option ".$select." value='".$key."'>".$value["name_with_type"]."</option>";
    }
}
function render_quan_huyen_option($tinh_thanh,$default = ""){
  $default = intval($default);
  $json = file_get_contents(get_stylesheet_directory()."/json/quan-huyen/".$tinh_thanh.".json");
  $quan_huyen = json_decode($json,true);  
  foreach ($quan_huyen as $key => $value) {
    if($key == $default){$select = "selected";}else{$select = "";}
    echo "<option ".$select." value='".$key."'>".$value["name_with_type"]."</option>";
  }  
}

Last updated