Tích hợp framework vô wordpress (ok)

https://github.com/dloewith/Nathan-MVC

Chú ý phải tạo folder ảnh sẵn như trên nó mới hoạt động :)

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\functions.php

<?php
add_action('after_setup_theme', 'blankslate_setup');
function blankslate_setup() {
  load_theme_textdomain('blankslate', get_template_directory() . '/languages');
  add_theme_support('title-tag');
  add_theme_support('post-thumbnails');
  add_theme_support('responsive-embeds');
  add_theme_support('automatic-feed-links');
  add_theme_support('html5', array('search-form', 'navigation-widgets'));
  add_theme_support('woocommerce');
  global $content_width;
  if (!isset($content_width)) {$content_width = 1920;}
  register_nav_menus(array('main-menu' => esc_html__('Main Menu', 'blankslate')));
}
add_action('admin_notices', 'blankslate_notice');
function blankslate_notice() {
  $user_id   = get_current_user_id();
  $admin_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $param     = (count($_GET)) ? '&' : '?';
  if (!get_user_meta($user_id, 'blankslate_notice_dismissed_7') && current_user_can('manage_options')) {
    echo '<div class="notice notice-info"><p><a href="' . esc_url($admin_url), esc_html($param) . 'dismiss" class="alignright" style="text-decoration:none"><big>' . esc_html__('Ⓧ', 'blankslate') . '</big></a>' . wp_kses_post(__('<big><strong>📝 Thank you for using BlankSlate!</strong></big>', 'blankslate')) . '<br /><br /><a href="https://wordpress.org/support/theme/blankslate/reviews/#new-post" class="button-primary" target="_blank">' . esc_html__('Review', 'blankslate') . '</a> <a href="https://github.com/tidythemes/blankslate/issues" class="button-primary" target="_blank">' . esc_html__('Feature Requests & Support', 'blankslate') . '</a> <a href="https://calmestghost.com/donate" class="button-primary" target="_blank">' . esc_html__('Donate', 'blankslate') . '</a></p></div>';
  }
}
add_action('admin_init', 'blankslate_notice_dismissed');
function blankslate_notice_dismissed() {
  $user_id = get_current_user_id();
  if (isset($_GET['dismiss'])) {
    add_user_meta($user_id, 'blankslate_notice_dismissed_7', 'true', true);
  }
}
add_action('wp_enqueue_scripts', 'blankslate_enqueue');
function blankslate_enqueue() {
  wp_enqueue_style('blankslate-style', get_stylesheet_uri());
  wp_enqueue_script('jquery');
  // Threaded comment reply styles.
  if (is_singular() && comments_open()) {
    wp_enqueue_script('comment-reply');
  }
}
function blankslate_footer() {
  ?>
<script>
jQuery(document).ready(function($) {
var deviceAgent = navigator.userAgent.toLowerCase();
if (deviceAgent.match(/(iphone|ipod|ipad)/)) {
$("html").addClass("ios");
$("html").addClass("mobile");
}
if (deviceAgent.match(/(Android)/)) {
$("html").addClass("android");
$("html").addClass("mobile");
}
if (navigator.userAgent.search("MSIE") >= 0) {
$("html").addClass("ie");
}
else if (navigator.userAgent.search("Chrome") >= 0) {
$("html").addClass("chrome");
}
else if (navigator.userAgent.search("Firefox") >= 0) {
$("html").addClass("firefox");
}
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
$("html").addClass("safari");
}
else if (navigator.userAgent.search("Opera") >= 0) {
$("html").addClass("opera");
}
});
</script>
<?php
}
add_filter('document_title_separator', 'blankslate_document_title_separator');
function blankslate_document_title_separator($sep) {
  $sep = esc_html('|');
  return $sep;
}
add_filter('the_title', 'blankslate_title');
function blankslate_title($title) {
  if ($title == '') {
    return esc_html('...');
  } else {
    return wp_kses_post($title);
  }
}
function blankslate_schema_type() {
  $schema = 'https://schema.org/';
  if (is_single()) {
    $type = "Article";
  } elseif (is_author()) {
    $type = 'ProfilePage';
  } elseif (is_search()) {
    $type = 'SearchResultsPage';
  } else {
    $type = 'WebPage';
  }
  echo 'itemscope itemtype="' . esc_url($schema) . esc_attr($type) . '"';
}
add_filter('nav_menu_link_attributes', 'blankslate_schema_url', 10);
function blankslate_schema_url($atts) {
  $atts['itemprop'] = 'url';
  return $atts;
}
if (!function_exists('blankslate_wp_body_open')) {
  function blankslate_wp_body_open() {
    do_action('wp_body_open');
  }
}
add_action('wp_body_open', 'blankslate_skip_link', 5);
function blankslate_skip_link() {
  echo '<a href="#content" class="skip-link screen-reader-text">' . esc_html__('Skip to the content', 'blankslate') . '</a>';
}
add_filter('the_content_more_link', 'blankslate_read_more_link');
function blankslate_read_more_link() {
  if (!is_admin()) {
    return ' <a href="' . esc_url(get_permalink()) . '" class="more-link">' . sprintf(__('...%s', 'blankslate'), '<span class="screen-reader-text">  ' . esc_html(get_the_title()) . '</span>') . '</a>';
  }
}
add_filter('excerpt_more', 'blankslate_excerpt_read_more_link');
function blankslate_excerpt_read_more_link($more) {
  if (!is_admin()) {
    global $post;
    return ' <a href="' . esc_url(get_permalink($post->ID)) . '" class="more-link">' . sprintf(__('...%s', 'blankslate'), '<span class="screen-reader-text">  ' . esc_html(get_the_title()) . '</span>') . '</a>';
  }
}
// == Start
add_filter('big_image_size_threshold', '__return_false');
add_filter('intermediate_image_sizes', 'remove_default_img_sizes', 10, 1);
function remove_default_img_sizes($sizes) {
  $targets = ['medium_large', 'large', '1536x1536', '2048x2048', 'woocommerce_thumbnail', 'woocommerce_single', 'woocommerce_gallery_thumbnail', 'shop_catalog', 'shop_single', 'shop_thumbnail'];
  foreach ($sizes as $size_index => $size) {
    if (in_array($size, $targets)) {
      unset($sizes[$size_index]);
    }
  }
  return $sizes;
}
add_action('wp_enqueue_scripts', 'ecademy_enqueue_style');
function ecademy_enqueue_style() {
  wp_enqueue_style("custom_css", get_stylesheet_directory_uri() . "/css/custom.css", array(), '1.1.0', 'all');
  $script_data_array = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'security' => wp_create_nonce( 'file_upload' )
  );
  wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '123', 'all', true);
  wp_localize_script( 'custom_js', 'fiuajax', $script_data_array );
}
function wpdocs_selectively_enqueue_admin_script( $hook ) {
   wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/js/admin.js', array('jquery'), '123', 'all', true);
   wp_enqueue_style("custom_css", get_stylesheet_directory_uri() . "/css/admin.css", array(), '1.1.0', 'all');
}
add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' );
add_action('init', 'reg_post_type');
function reg_post_type() {
  register_post_type('court', array(
    'labels'             => array(
      'name'          => 'Court',
      'singular_name' => 'Court',
    ),
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'query_var'          => true,
    'rewrite'            => true,
    'capability_type'    => 'post',
    'hierarchical'       => false,
    'supports'           => array(
      'title', 'thumbnail', 'comments', 'author',
    ),
  )
  );
};
// ==
function add_gallery_post_type_court($post_type) {
  $post_types = array('court');
  if (in_array($post_type, $post_types)) {
    add_meta_box(
      'list_gallery',
      'Gallery',
      'gallery_post_type_court',
      $post_type,
      'advanced',
      'high'
    );
  }
}
add_action('add_meta_boxes', 'add_gallery_post_type_court');
function gallery_post_type_court() {
  $list_gallery = json_decode(get_post_meta(get_the_ID(), 'list_gallery', true), true);
  ?>
  <table class="wp-list-table widefat striped table-view-list posts at-table-banner">
    <tr>
      <th>IMAGES</th><th style="width: 50px;">action</th>
    </tr>
    <?php if (!empty($list_gallery)): ?>
      <?php 
      for ($i = 0; $i < count($list_gallery); $i++) {
      $image = wp_get_attachment_image_src($list_gallery[$i]);?>
        <tr class="at-row-track">
          <td>
            <div class="wrap_img">
              <a href="#" class="at-upload button">Change image</a>
              <div class="preview_img"><img src="<?php echo $image[0]; ?>"></div>
              <input class = "at-input" type="hidden" required name="list_gallery[]" value="<?php echo $list_gallery[$i] ?>">
            </div>
          </td>
          <td><span style="position: inherit;display: block;padding: 5px 0;" class="notice-dismiss at-remove-row-group"></span></td>
        </tr>
      <?php } else : ?>
      <tr class="at-row-track">
        <td>
          <div class="wrap_img">
            <a href="#" class="at-upload button">Add image</a>
            <div class="preview_img"></div>
            <input class = "at-input" type="hidden" required name="list_gallery[]" value="">
          </div>
        </td>
        <td><span style="position: inherit;display: block;padding: 5px 0;" class="notice-dismiss at-remove-row-group"></span></td>
      </tr>
    <?php endif;?>
  </table>
  <?php
  $row_group = '<tr class="at-row-track"><td><div class="wrap_img"><a href="#" class="at-upload button">Add image</a><div class="preview_img"></div><input class = "at-input" type="hidden" required name="list_gallery[]" value=""></div></td><td><span style="position: inherit;display: block;padding: 5px 0;" class="notice-dismiss at-remove-row-group"></span></td></tr>';
  ?>
    <span style="cursor: pointer;margin-top:10px;" class="button add_row_group">Add image</span>
    <script type="text/javascript">
      jQuery(document).ready(function($){
        $(".add_row_group").click(function(){
         $(".at-table-banner tbody").append('<?php echo $row_group ?>');
        });
        $('body').on('click','.notice-dismiss', function () {
          $(this).closest(".at-row-track").remove();
        })
      })
    </script>
  <?php
}
function at_save_gallery_court($post_id) {
  if (isset($_POST["list_gallery"])) {
    update_post_meta($post_id, "list_gallery", json_encode($_POST["list_gallery"]));
  }
}
add_action('save_post', 'at_save_gallery_court');
// ==
include_once "framework/define.php";
include_once "framework/lib.php";
include_once "framework/setting.php";
require_once 'framework/framework.php';
global $bj_controller;
$bj_controller = new BJ_Controller();
include_once "framework/ajax/app.php";
include_once "framework/ajax/court.php";

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\define.php

<?php
define('BJ_NONCE_KEY', "BJWPNOCEcakgdragon2");
if (!defined('THEME_URL')) {
  define('THEME_URL', trailingslashit(esc_url(get_template_directory_uri())));
}
if (!defined('SITE_URL')) {
  define('SITE_URL', trailingslashit(esc_url(get_site_url())));
}
define('USER', "subscriber");

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\lib.php

<?php
function upload_image($file){
  $targetDir = wp_upload_dir()["basedir"].'/image-files/'; 
  $allowTypes = array( 'jpg', 'png', 'jpeg'); 
  $fileName = round(microtime(true))."_".basename($file['name']);
  $targetFilePath = $targetDir.$fileName; 
  // Check whether file type is valid 
  $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); 
  if(in_array($fileType, $allowTypes)){ 
      if($file["size"] > 10000000) return array("status" => "error","content" => "Maximum 10Mb");
      if(move_uploaded_file($file['tmp_name'], $targetFilePath)){ 
        resize_image('crop',$targetDir.$fileName,$targetDir.'200x200/'.$fileName,200,200);
        $file_id = bj_model_insert_img($fileName);
        return array("status" => "success","content" => $file_id);
      } 
  }else{
    return array("status" => "error","content" => "Allow jpg, png, jpeg");
  }
}
function bj_model_insert_img($file_name){
  global $wpdb;
  $table = $wpdb->prefix.'bj_image';
  $data = array('image_name' => $file_name);
  $format = array('%s');
  $wpdb->insert($table,$data,$format);
  return  $wpdb->insert_id;
}
function get_image_url_by_id($id,$size = "full"){
  $url = wp_get_upload_dir()["baseurl"]."/image-files/";
  if($size != "full") $url = wp_get_upload_dir()["baseurl"]."/image-files/200x200/";
  global $wpdb;
  $table = $wpdb->prefix."bj_image";
  $result = $wpdb->get_results (  $wpdb->prepare(" SELECT image_name  FROM  {$table} WHERE id = %d ",$id ), ARRAY_A , 1 );
  return $url.$result[0]["image_name"];
}
function delete_img_by_id($img_id){
  global $wpdb;
  $table = $wpdb->prefix."bj_image";
  $result = $wpdb->get_results (  $wpdb->prepare(" SELECT image_name  FROM  {$table} WHERE id = %d ",$img_id ), ARRAY_A , 1 );
  $file_name = $result[0]["image_name"];
  $folder = wp_upload_dir()["basedir"].'/image-files/';
  unlink($folder.$file_name);
  unlink($folder."200x200/".$file_name);
  $wpdb->delete( $table, array( 'id' => $img_id ),array( '%d') );
}


function get_average_rating($courtId){
  $total_rate = 0;
  $number_comment= get_comments_number($courtId);
  if ($number_comment == 0) return 0;
  $args = array(
    'post_id' => $courtId,
    'status' => 'approve',
    'hierarchical' => false,
  );
  $comments = get_comments( $args ); 
  if($comments){
    foreach ($comments  as $comment){
      $rate_number = get_comment_meta( $comment->comment_ID, 'rating', true );
      if($rate_number){
        $total_rate += (int)$rate_number;
      }
    }
  }
  $average = $total_rate / $number_comment;
  return $average;
}
function percentage_on_court($courtId){
  $number_comment= get_comments_number($courtId);
  if($number_comment == 0){
    return [
      'average' => 0,
      'count' => 0,
      'width' => 0
    ]; 
  }
  $average = get_average_rating($courtId);
  $width_rating = ($average / 5) * 100;
  if($width_rating > 0) $width_rating = round($width_rating);
  if($average > 0) $average = round($average);
  return [
    'average' => $average,
    'count' => $number_comment,
    'width' => $width_rating
  ];
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\setting.php

<?php
add_action('init', 'my_custom_dashboard_access_handler');
function my_custom_dashboard_access_handler() {
  // Check if the current page is an admin page
  // && and ensure that this is not an ajax call
  if (is_admin() && !(defined('DOING_AJAX') && DOING_AJAX)) {
    //Get all capabilities of the current user
    $user = get_userdata(get_current_user_id());
    $caps = (is_object($user)) ? array_keys($user->allcaps) : array();
    //All capabilities/roles listed here are not able to see the dashboard
    $block_access_to = array(USER);
    if (array_intersect($block_access_to, $caps)) {
      wp_redirect(get_site_url());
    }
  }
}
add_action('after_setup_theme', 'disable_admin_bar');
function disable_admin_bar() {
  if (current_user_can(USER)) {
    show_admin_bar(false);
  }
  ;
}
function resize_image($method, $image_loc, $new_loc, $width, $height) {
  $exif = exif_read_data($image_loc);
  if (isset($exif['Orientation']) && $exif['Orientation'] === 6) {
    $rotate = -90;
  } else if (isset($exif['Orientation']) && $exif['Orientation'] === 3) {
    $rotate = 180;
  } else if (isset($exif['Orientation']) && $exif['Orientation'] === 8) {
    $rotate = 90;
  }
  if (!is_array(@$GLOBALS['errors'])) {$GLOBALS['errors'] = array();}
  if (!in_array($method, array('force', 'max', 'crop'))) {$GLOBALS['errors'][] = 'Invalid method selected.';}
  if (!$image_loc) {$GLOBALS['errors'][] = 'No source image location specified.';} else {
    if ((substr(strtolower($image_loc), 0, 7) == 'http://') || (substr(strtolower($image_loc), 0, 7) == 'https://')) { /*don't check to see if file exists since it's not local*/} elseif (!file_exists($image_loc)) {$GLOBALS['errors'][] = 'Image source file does not exist.';}
    $extension = strtolower(substr($image_loc, strrpos($image_loc, '.')));
    if (!in_array($extension, array('.jpg', '.jpeg', '.png', '.gif', '.bmp'))) {$GLOBALS['errors'][] = 'Invalid source file extension!';}
  }
  if (!$new_loc) {$GLOBALS['errors'][] = 'No destination image location specified.';} else {
    $new_extension = strtolower(substr($new_loc, strrpos($new_loc, '.')));
    if (!in_array($new_extension, array('.jpg', '.jpeg', '.png', '.gif', '.bmp'))) {$GLOBALS['errors'][] = 'Invalid destination file extension!';}
  }
  $width = abs(intval($width));
  if (!$width) {$GLOBALS['errors'][] = 'No width specified!';}
  $height = abs(intval($height));
  if (!$height) {$GLOBALS['errors'][] = 'No height specified!';}
  if (count($GLOBALS['errors']) > 0) {echo_errors();return false;}
  if (in_array($extension, array('.jpg', '.jpeg'))) {$image = @imagecreatefromjpeg($image_loc);} elseif ($extension == '.png') {$image = @imagecreatefrompng($image_loc);} elseif ($extension == '.gif') {$image = @imagecreatefromgif($image_loc);} elseif ($extension == '.bmp') {$image = @imagecreatefromwbmp($image_loc);}
  if (!$image) {$GLOBALS['errors'][] = 'Image could not be generated!';} else {
    $current_width  = imagesx($image);
    $current_height = imagesy($image);
    if ((!$current_width) || (!$current_height)) {$GLOBALS['errors'][] = 'Generated image has invalid dimensions!';}
  }
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);
    echo_errors();return false;}
  if ($method == 'force') {$new_image = resize_image_force($image, $width, $height);} elseif ($method == 'max') {$new_image = resize_image_max($image, $width, $height);} elseif ($method == 'crop') {$new_image = resize_image_crop($image, $width, $height);}
  if ((!$new_image) && (count($GLOBALS['errors'] == 0))) {$GLOBALS['errors'][] = 'New image could not be generated!';}
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);
    echo_errors();return false;}
  $save_error = false;
  if (in_array($extension, array('.jpg', '.jpeg'))) {
    if (isset($rotate)) {$new_image = imagerotate($new_image, $rotate, 0);}
    imagejpeg($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.png') {
    if (isset($rotate)) {$new_image = imagerotate($new_image, $rotate, 0);}
    imagepng($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.gif') {imagegif($new_image, $new_loc) or ($save_error = true);} elseif ($extension == '.bmp') {imagewbmp($new_image, $new_loc) or ($save_error = true);}
  if ($save_error) {$GLOBALS['errors'][] = 'New image could not be saved!';}
  if (count($GLOBALS['errors']) > 0) {
    @imagedestroy($image);@imagedestroy($new_image);
    echo_errors();return false;}
  imagedestroy($image);
  imagedestroy($new_image);
  return true;
}
function echo_errors() {
  if (!is_array(@$GLOBALS['errors'])) {$GLOBALS['errors'] = array('Unknown error!');}
  foreach ($GLOBALS['errors'] as $error) {echo '<p style="color:red;font-weight:bold;">Error: ' . $error . '</p>';}
}
function resize_image_force($image, $width, $height) {
  $w = @imagesx($image); //current width
  $h = @imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w == $width) && ($h == $height)) {return $image;} //no resizing needed
  $image2 = imagecreatetruecolor($width, $height);
  imagecopyresampled($image2, $image, 0, 0, 0, 0, $width, $height, $w, $h);
  return $image2;
}
function resize_image_max($image, $max_width, $max_height) {
  $w = imagesx($image); //current width
  $h = imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w <= $max_width) && ($h <= $max_height)) {return $image;} //no resizing needed
  //try max width first...
  $ratio = $max_width / $w;
  $new_w = $max_width;
  $new_h = $h * $ratio;
  //if that didn't work
  if ($new_h > $max_height) {
    $ratio = $max_height / $h;
    $new_h = $max_height;
    $new_w = $w * $ratio;
  }
  $new_image = imagecreatetruecolor($new_w, $new_h);
  imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
  return $new_image;
}
function resize_image_crop($image, $width, $height) {
  $w = @imagesx($image); //current width
  $h = @imagesy($image); //current height
  if ((!$w) || (!$h)) {$GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.';return false;}
  if (($w == $width) && ($h == $height)) {return $image;} //no resizing needed
  //try max width first...
  $ratio = $width / $w;
  $new_w = $width;
  $new_h = $h * $ratio;
  //if that created an image smaller than what we wanted, try the other way
  if ($new_h < $height) {
    $ratio = $height / $h;
    $new_h = $height;
    $new_w = $w * $ratio;
  }
  $image2 = imagecreatetruecolor($new_w, $new_h);
  imagecopyresampled($image2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
  //check to see if cropping needs to happen
  if (($new_h != $height) || ($new_w != $width)) {
    $image3 = imagecreatetruecolor($width, $height);
    if ($new_h > $height) {
      //crop vertically
      $extra = $new_h - $height;
      $x     = 0; //source x
      $y     = round($extra / 2); //source y
      imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
    } else {
      $extra = $new_w - $width;
      $x     = round($extra / 2); //source x
      $y     = 0; //source y
      imagecopyresampled($image3, $image2, 0, 0, $x, $y, $width, $height, $width, $height);
    }
    imagedestroy($image2);
    return $image3;
  } else {
    return $image2;
  }
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\framework.php

<?php
class Pv_Controller{  
  public function load(){
    global $bj_controller;
    return $bj_controller;
  }
}
class BJ_Controller{
  public function Controller($file_name = ""){
    $obj = new stdClass();
    $file_url = "controller/" .$file_name. ".php";
    require_once $file_url;
    $controller_name = "BJ_".$file_name."_Controller";
    $obj = new $controller_name ();
    return $obj;
  }
  public function Model($file_name = ""){
    $obj = new stdClass();
    $file_url = "model/" .$file_name. ".php";
    require_once $file_url;
    $model_name = "BJ_".$file_name."_Model";
    $obj = new $model_name ();
    return $obj;
  }
  public function View($file_name = "",$data = array(),$path = ""){
    $file_name = $path."/".$file_name;
    get_template_part( "framework/view/" .$file_name,"",$data); 
  }
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\ajax\app.php

<?php
add_action('wp_ajax_app_update_post', 'app_update_post');
function app_update_post() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['edit_post']) or !wp_verify_nonce($_POST['edit_post'], BJ_NONCE_KEY . 'edit_post' . $current_user_id)) {
    die("Token");
  }
  $content               = trim($_POST['edit-feed-content']);
  $post_id               = strip_tags($_POST["post_id"]);
  $delete_current_img    = $_POST['remove_image'];
  $delete_before_img     = $_POST['remove_image_title'];
  $arr_delete_before_img = explode(',', $delete_before_img);
  $list_images_post_arr  = json_decode(get_post_meta($post_id, "img_single_community", true), true);
  if (empty($list_images_post_arr)) {
    $list_images_post_arr = [];
  }
  $my_post = array(
    'ID'           => $post_id,
    'post_content' => $content,
  );
  $result_edit = wp_update_post($my_post);
  if ($result_edit) {
    setcookie("edit_post", "1", time() + 360, "/", "", 0);
  }
  if (!empty($delete_current_img)) {
    $arr_id_img = explode(',', $delete_current_img);
    if (!empty($arr_id_img)) {
      foreach ($arr_id_img as $key => $value) {
        delete_img_by_id($value);
        if (($key = array_search($value, $list_images_post_arr)) !== false) {
          unset($list_images_post_arr[$key]);
        }
      }
      update_post_meta($post_id, 'img_single_community', json_encode($list_images_post_arr));
    }
  }
  //Save attach
  if (isset($_FILES['upload_files'])) {
    $attachment_img = array();
    $devvn_files    = $_FILES['upload_files'];
    for ($i = 0; $i < sizeof($_FILES['upload_files']['name']); $i++) {
      if (!in_array($i + 1, $arr_delete_before_img)) {
        if ($devvn_files['size'][$i] > 0 && $devvn_files['error'][$i] == 0) {
          $file = array(
            'name'     => $devvn_files['name'][$i],
            'type'     => $devvn_files['type'][$i],
            'tmp_name' => $devvn_files['tmp_name'][$i],
            'error'    => $devvn_files['error'][$i],
            'size'     => $devvn_files['size'][$i],
          );
          $result_upload = upload_image($file);
          if ($result_upload['status'] == 'success') {
            array_push($list_images_post_arr, $result_upload["content"]);
          }
        }
      }
    }
    unset($_FILES);
    if (!empty($list_images_post_arr)) {
      update_post_meta($post_id, 'img_single_community', json_encode($list_images_post_arr));
    }
  }
  echo "success";
  die();
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\ajax\court.php

<?php
//add_review_single_court
add_action('wp_ajax_add_review_single_court', 'add_review_single_court');
function add_review_single_court() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token_add_review']) or !wp_verify_nonce($_POST['token_add_review'], BJ_NONCE_KEY . 'add-review' . $current_user_id)) {
    die("Token");
  }
  $idCourt                      = intval($_POST['idCourt']);
  $comment_content              = strip_tags($_POST['text-content']);
  $rate                         = intval($_POST['rate']);
  $current_list_images_post_arr = [];
  $dts                          = $_POST['dts'];
  $ttt                          = explode(',', $dts);
  $data                         = array(
    'user_id'          => $current_user_id,
    'comment_post_ID'  => $idCourt,
    'comment_date'     => date('Y-m-d H:i:s'),
    'comment_date_gmt' => date('Y-m-d H:i:s'),
    'comment_approved' => 1,
    'comment_content'  => $comment_content,
  );
  if (!empty($comment_content)) {
    $id_comment = wp_insert_comment($data);
  }
  if ($id_comment) {
    $result_rate = add_comment_meta($id_comment, 'rating', $rate);
    if ($result_rate) {
      echo 'success';
    }
  }
  if ($id_comment && isset($_FILES["upload_files"])) {
    for ($i = 0; $i < sizeof($_FILES['upload_files']['name']); $i++) {
      if (in_array($i + 1, $ttt)) {
      } else {
        if ($_FILES['upload_files']['name'][$i]) {
          $file = array(
            'name'     => $_FILES['upload_files']['name'][$i],
            'type'     => $_FILES['upload_files']['type'][$i],
            'tmp_name' => $_FILES['upload_files']['tmp_name'][$i],
            'error'    => $_FILES['upload_files']['error'][$i],
            'size'     => $_FILES['upload_files']['size'][$i],
          );
        }
        $result_upload = upload_image($file);
        if ($result_upload['status'] == 'success') {
          array_push($current_list_images_post_arr, $result_upload["content"]);
        }
      }
    }
    if (!empty($current_list_images_post_arr)) {
      add_comment_meta($id_comment, 'list_img_rating', json_encode($current_list_images_post_arr));
    }
  }
  wp_die();
}
//search_court_name
add_action('wp_ajax_search_court_name', 'search_court_name');
function search_court_name() {
  $current_user_id = get_current_user_id();
  if (!isset($_POST['token']) or !wp_verify_nonce($_POST['token'], BJ_NONCE_KEY . $current_user_id . 'search-court')) {
    die("Token-court");
  }
  $key  = strip_tags($_POST["key"]);
  $args = array(
    'post_type'      => 'court',
    'post_status'    => 'publish',
    's'              => $key,
    'posts_per_page' => -1,
  );
  $query = new WP_Query($args);
  if ($query->have_posts()):
    while ($query->have_posts()): $query->the_post();
      get_template_part('layout/item', 'court');
    endwhile;
    wp_reset_query();
  else:
    echo __("Not found", "dragon");
  endif;
  wp_die();
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\controller\court.php

<?php
class BJ_court_Controller extends Pv_Controller {
  public function court() {
    $data = [];
    $this->load()->View("detail", "", "court");
  }
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\framework\controller\list.php

<?php
class BJ_list_Controller extends Pv_Controller {
  public function list() {
    $data = [];
    $this->load()->View("list", "", "court");
  }
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?> <?php blankslate_schema_type(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>
<div id="wrapper" class="hfeed">
<div id="container">
<main id="content" role="main">

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\footer.php

</main>
</div>
</div>
<?php wp_footer(); ?>
</body>
</html>

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\single-court.php

<?php get_header() ?>
<!-- Main Contents -->
<div class="main_content">
	<div class="mcontainer">
    <?php  
    	require_once 'framework/frontend.php';
      new BJ_Frontend();
    ?>
	</div>
</div>
<?php get_footer() ?>

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\page-list.php

<?php get_header() ?>
<!-- Main Contents -->
<div class="main_content">
  <div class="mcontainer">
    <?php  
      require_once 'framework/frontend.php';
      new BJ_Frontend();
    ?>
  </div>
</div>
<?php get_footer() ?>

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\js\admin.js

jQuery(function($) {
  $('body').on('click', '.at-upload', function(e) {
    e.preventDefault();
    var button = $(this),
      custom_uploader = wp.media({
        title: 'Insert image',
        library: {
          // uploadedTo : wp.media.view.settings.post.id, // attach to the current post?
          type: 'image'
        },
        button: {
          text: 'Use this image'
        },
        multiple: false
      }).on('select', function() { // it also has "open" and "close" events
        var attachment = custom_uploader.state().get('selection').first().toJSON();
        button.text('Change image').next().html('<img src="' + attachment.url + '">').next().val(attachment.id);
      }).open();
  });
});

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\js\custom.js

var dts = [];
function removeParam(key, sourceURL) {
  var rtn = sourceURL.split("?")[0],
    param,
    params_arr = [],
    queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
  if (queryString !== "") {
    params_arr = queryString.split("&");
    for (var i = params_arr.length - 1; i >= 0; i -= 1) {
      param = params_arr[i].split("=")[0];
      if (param === key) {
        params_arr.splice(i, 1);
      }
    }
    if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
  }
  return rtn;
}
jQuery(document).ready(function($) {
  $('.menu-tab .tab-a').click(function(e) {
    e.preventDefault();
    $('.menu-tab li').removeClass('active')
    $(".tab").removeClass('tab-active');
    $(".tab[data-tab-id='" + $(this).attr('data-id') + "']").addClass("tab-active");
    $(".tab-a").removeClass('active');
    $(this).parent().addClass('active');
  });
  $('.profile .tab-a').click(function(e) {
    e.preventDefault();
    $(".tab").removeClass('tab-active');
    $(".tab[data-tab-id='" + $(this).attr('data-id') + "']").addClass("tab-active");
    $(".tab-a").removeClass('active');
    $(this).parent().find(".tab-a").addClass('active');
  });
  $('.bnt-review').click(function(e) {
    e.preventDefault();
    $('#review-modal').addClass('active');
  });
  $('.modal-close').click(function(e) {
    e.preventDefault();
    $('#review-modal').removeClass('active');
  });
  // review ajax
  $('input[name="rate"]').change(function() {
    $('#form-review-group-modal button').prop("disabled", false);
  });
  $("body").on("submit", "form#form-review-group-modal", function(e) {
    e.preventDefault();
    let rate = $('input[name="rate"]:checked').val();
    var formData = new FormData(document.getElementById("form-review-group-modal"));
    formData.append('action', 'add_review_single_court');
    formData.append("dts", dts);
    if (rate) {
      $("body").addClass("app-loading");
      $.ajax({
        type: "post",
        url: fiuajax.ajaxurl,
        data: formData,
        contentType: false,
        processData: false,
        success: function(response) {
          $("body").removeClass("app-loading");
          if (response == "success") {
            //window.appBridge.close();
            var alteredURL = removeParam("appt", window.location.href) + "?appt=C&app_back=true";
            window.location.replace(alteredURL);
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          $("body").removeClass("app-loading");
          console.log('error');
        }
      })
    }
  });
  // ==
  var xp = 0;
  var input_btn = 0;
  var l = $(".bj-gr-input-file"),
    t = $(".form-group.list_attach");
  function cl() {
    $(".form-group", l).length <= 5 && 0 <= $(".form-group", l).length ? t.addClass("show-btn") : t.removeClass("show-btn");
  }
  $(document).on("click", ".at-add-image-btn", function(e) {
    cl();
    let leg_current = $(".bj-gr-input-file .form-group").length;
    if (leg_current >= 6) {
      alert("Maximum 6 images");
      return;
    } else {
      input_btn++;
      $(".list_input").append(
        "<input type='file' style='display:none;' 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 leg_current = $(".bj-gr-input-file .form-group").length;
    files = e.target.files;
    filesLength = files.length;
    if (filesLength + leg_current >= 7) {
      alert("Maximum 6 images");
      return
    }
    for (var i = 0; i < filesLength; i++) {
      xp++;
      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) {
        var file = e.target;
        $(".bj-gr-input-file").append(
          "<div class='form-group bj-form-group" +
          xp +
          "'><i deltsid='" + 0 + "' data-title='" + file.name + "' class='cancel_mutile_image fa fa-times at-remove-input' title='Remove' aria-hidden='true'></i><div class='at_item_image background_v" +
          xp +
          "' style='background-image: url(" +
          e.target.result +
          ")'></div></div>"
        );
      };
      fileReader.readAsDataURL(f);
    }
  });
  var rty = 0;
  $(document).on("click", ".cancel_mutile_image.at-remove-input", function(e) {
    $('.cancel_mutile_image').each(function() {
      chk_id = $(this).attr('deltsid');
      if (chk_id == 0) {
        rty++;
        $(this).attr('deltsid', rty);
      }
    });
    deltsid = $(this).attr('deltsid');
    dts.push(deltsid);
    $(this).closest(".form-group").remove();
    $('#remove_image_title').val(dts);
    cl();
  });
  // Search
  $("#court__search-input").keyup(function() {
    let wrap_output = $('.court__list');
    let key = $('#court__search-input').val();
    key = key.trim()
    if (key.length > 1) {
      wrap_output.css('opacity', '0.6');
      $.ajax({
        url: fiuajax.ajaxurl,
        type: "post",
        dataType: "html",
        data: {
          action: 'search_court_name',
          key: key,
          token: $(this).data('token'),
        },
        success: function(output) {
          wrap_output.css('opacity', '1')
          if (output)
            $('.court__list').html(output)
        },
      });
    }
  });
});

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\images

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\css\custom.scss

a {
  text-decoration: none;
  &.contact {
    color: #fff;
    background: #FEAC27;
    padding: .5rem 1rem;
    span {
      margin-left: .8rem;
    }
  }
}
.menu-tab {
  ul {
    border-bottom: 1px solid #E9E9E9;
    border-bottom: 1px solid #E9E9E9;
    li.active {
      border-bottom: 2px solid #6669F1;
      border-bottom: 2px solid #6669F1;
      a {
        font-weight: 500;
      }
    }
  }
  li {
    padding-bottom: .7rem;
    width: 33.3333%;
    padding-bottom: .7rem;
    a.active {
      color: #2a41e8;
      border-bottom: 3px solid #2a41e8;
    }
  }
}
.tab {
  min-height: 150px;
  display: none;
}
.tab-active {
  display: block;
}
.d-flex.tab-active {
  display: flex;
}
.create-post {
  -webkit-box-align: start;
  -ms-flex-align: start;
  align-items: flex-start;
  padding-top: 100px;
  display: none;
  &.uk-modal {
    form input, button.btn.dropdown-toggle {
      background: #f3f4f6;
    }
  }
  input {
    background: #f3f4f6;
  }
  &.active {
    display: -webkit-box !important;
    display: -ms-flexbox !important;
    display: flex !important;
    z-index: 1;
    display: -webkit-box !important;
    display: -ms-flexbox !important;
    display: flex !important;
    z-index: 1;
    background-color: #fff;
    padding: 0px;
    width: 100%;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    height: 100%;
    top: 0;
    position: fixed;
    left: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
  }
  .bootstrap-select {
    &.btn-group {
      button {
        height: 38px;
        max-width: 168px !important;
        -webkit-box-shadow: none;
        box-shadow: none;
        padding: 0;
      }
      .dropdown-toggle {
        .filter-option {
          line-height: 35px;
          max-width: 100%;
          border-radius: 0.375rem;
        }
        .caret {
          left: 0;
        }
      }
    }
    &:before {
      background: transparent;
    }
  }
  .dropdown-menu.open {
    width: 210px !important;
    border: 1px solid #f1f3f4;
    -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 10px 25px -5px, rgba(0, 0, 0, 0.04) 0px 13px 10px -5px;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 10px 25px -5px, rgba(0, 0, 0, 0.04) 0px 13px 10px -5px;
  }
}
.nearby .flex {
  overflow: hidden;
}
.md\:grid-cols-5 {
  grid-template-columns: repeat(5, minmax(0, 1fr));
}
.court__search__box {
  position: relative;
  i {
    position: absolute;
    pointer-events: none;
    top: 50%;
    left: calc(5% + 15px);
    transform: translateY(-50%);
  }
}
.court__search input {
  background: #f1f3f4;
  padding-left: 35px;
}
.card-media {
  height: 350px;
  width: 100%;
  margin-bottom: 15px;
  img {
    height: 100%;
    width: 100%;
    object-fit: cover;
  }
}
.court__item {
  overflow: hidden;
  padding-left: 0;
  .box-text {
    margin-left: 1rem;
  }
}
.court__list .court__item {
  &:not(:last-child) {
    border-bottom: 1px solid #e2dfdf;
  }
  h4 {
    font-weight: bold;
  }
}
#court__search-input {
  height: 40px;
  border-radius: 20px;
  margin: 0 auto;
  overflow: hidden;
  width: 90%;
}
#review-modal {
  a.at-add-image-btn {
    border: 1px solid #e5e7eb;
    padding: 0.5rem 1rem;
    color: #2a41e8 !important;
    border: 1px solid #e5e7eb;
    text-align: center;
    display: block;
    margin: 30px auto 0 auto;
    width: 150px;
  }
  textarea {
    box-shadow: none;
    border: 1px solid #e5e7eb;
  }
}
.group-input {
  margin-bottom: 30px;
}
span {
  &.at-add-image-btn {
    display: flex;
    width: 50%;
    height: 100px;
    border: 2px dashed #ccc;
    line-height: 100px;
    i {
      width: 100%;
      text-align: center;
      font-size: 50px;
    }
  }
  &.at_insert_attach {
    align-items: center;
    width: 80px;
    height: 80px;
    text-align: center;
    display: inline-block;
    float: left;
    border: 2px dashed #ccc;
    line-height: 76px;
    font-size: 25px;
    color: #ccc;
    display: none;
  }
}
.wp-list-table td {
  vertical-align: middle;
}
.wrap_img {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.preview_img {
  margin-left: 30px;
  img {
    width: 200px;
  }
}
.modal-close {
  position: absolute;
  top: 50%;
  right: 10px;
  padding: 5px;
  transform: translateY(-50%);
}
.featured-media, .featured-image {
  width: 100%;
  margin: 0 auto;
  height: 350px;
  max-width: 100%;
}
.featured-media img, .featured-image img {
  width: 100%;
  object-fit: cover;
  height: 100%;
}
.single-court {
  svg, > i {
    min-width: 100%;
  }
  .box-title {
    h1 {
      font-size: 1.6rem;
      font-weight: bold;
      color: #000;
    }
    strong {
      color: #6669F1;
    }
  }
  .detail__box svg {
    min-width: 16px;
    width: 16px;
  }
  .detail {
    position: relative;
  }
}
.detail__list li {
  margin-bottom: 0.5rem;
  span {
    margin-left: .8rem;
  }
}
tilities__item.flex, .list-img.flex, .revies__item__image.flex {
  flex-wrap: wrap;
}
.utilities__item li {
  max-width: 50%;
  -ms-flex-preferred-size: 50%;
  flex-basis: 50%;
  margin-bottom: 1rem;
}
.list-img.flex, .revies__item__image.flex {
  justify-content: flex-start;
}
.list-img {
  &.flex a {
    display: block;
    max-width: 32%;
    -ms-flex-preferred-size: 32%;
    flex-basis: 32%;
    margin-bottom: 0.3rem;
    margin-left: 0.3rem;
  }
  > a {
    flex-grow: 1;
    max-width: 50%;
    > img {
      width: 100%;
      object-fit: cover;
    }
  }
}
.at_item_image {
  background-color: #333;
  background-position: 50%;
  background-size: cover;
  margin-bottom: 2px;
  padding-bottom: 50%;
  height: 100px;
}
.bj-gr-input-file > .form-group {
  flex-grow: 1;
  width: 50%;
  max-width: 50%;
  position: relative;
  float: left;
}
.form-group .at-remove-input {
  position: absolute;
  right: 0;
  top: 0;
  background: #000;
  color: #fff !important;
  border-radius: 50%;
  z-index: 2;
  display: block;
  width: 22px;
  height: 22px;
  font-size: 13px;
  text-align: center;
  line-height: 22px;
  cursor: pointer !important;
  opacity: 1 !important;
  text-shadow: none;
}
.u .utilities__item li span {
  margin-left: .8rem;
}
.revies__item__user .user-info {
  margin-left: 1rem;
}
.user-info h6 {
  font-weight: bold;
}
.revies__item__image a {
  display: block;
  max-width: 48%;
  -ms-flex-preferred-size: 48%;
  flex-basis: 48%;
  margin-bottom: 0.4rem;
  margin-left: 0.4rem;
}
.bnt-review {
  a, i {
    color: #2a41e8;
  }
}
.rate {
  float: left;
  height: 46px;
  padding: 0 10px;
  &:not(:checked) > {
    input {
      position: absolute;
      top: -9999px;
    }
    label {
      float: right;
      width: 1em;
      overflow: hidden;
      white-space: nowrap;
      cursor: pointer;
      font-size: 30px;
      color: #ccc;
      &:before {
        content: '★ ';
      }
      &:hover {
        color: #deb217;
        ~ label {
          color: #deb217;
        }
      }
    }
  }
  > {
    input:checked {
      ~ label {
        color: #ffc700;
      }
      + label:hover, ~ label:hover, + label:hover ~ label, ~ label:hover ~ label {
        color: #c59b08;
      }
    }
    label:hover ~ input:checked ~ label {
      color: #c59b08;
    }
  }
}
.revies__item__star {
  unicode-bidi: bidi-override;
  color: #ccc;
  font-size: 1.2rem;
  position: relative;
}
.fill-ratings {
  color: #FF9500;
  padding: 0;
  position: absolute;
  z-index: 1;
  display: block;
  top: 0;
  left: 0;
  overflow: hidden;
}
.empty-ratings {
  padding: 0;
  display: block;
  z-index: 0;
}

C:\xampp\htdocs\wordpress4\wp-content\themes\addframwork\css\admin.scss

.preview_img {
  width: 450px;
  img {
    width: 100%;
    max-width: 100%;
    object-fit: cover;
  }
}

Last updated

Was this helpful?