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

Edit Community

C:\xampp\htdocs\reset4\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_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_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>';
  }
}
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;
}
// == Start Script
add_action('wp_enqueue_scripts', 'ecademy_enqueue_style');
function ecademy_enqueue_style() {
  wp_enqueue_script('jquery');
  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( 'jquery-ui-datepicker' );
  wp_enqueue_script('bootstrap_js', get_stylesheet_directory_uri() . '/js/bootstrap.bundle.min.js', array('jquery'), '123', 'all', true);
  wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), '123', 'all', true);
  wp_localize_script('custom_js', 'app', $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');
// Community
register_post_type( 'community',
  array(
    'labels'              => array(
      'add_new_item'       => __( 'Add community', "umm" ),
      'name'               => __( 'Community', "umm" ),
      'singular_name'      => __( 'community', "umm" ),
      'edit_item'          => __( 'Edit community', "umm" ),
      'view_item'          => __( 'View community', "umm" ),
      'search_items'       => __( 'Search community', "umm" ),
      'not_found'          => __( 'No community found', "umm" ),
      'not_found_in_trash' => __( 'No community found in Trash', "umm" ),
    ),
    'public'              => true,
    'has_archive'         => false,
    'show_in_menu'        => true,
    'supports'            => array('editor', 'title', 'comments','excerpt','thumbnail'),
    'rewrite'             => array( 'slug' => '' ),
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'query_var'           => true,
    'capability_type'     => 'post',
    'hierarchical'        => true,
    'menu_position'       => null,
    'show_in_rest'        => true,
    'menu_icon'           => 'dashicons-format-chat',
  )
);
/**
 * Register a taxonomy Group
 *
 * @link http://codex.wordpress.org/Function_Reference/register_taxonomy
 */
function register_taxonomy_group_community() {
  $labels = array(
    'name' => 'Group',
    'singular_name' => 'Group',
    'menu_name' => 'Groups',
    'all_items' => 'All Groups',
    'edit_item' => 'Edit Group',
    'view_item' => 'View Group',
    'update_item' => 'Update Group',
    'add_new_item' => 'Add New Group',
    'new_item_name' => 'New Group Name',
    'parent_item' => 'Parent Group',
    'parent_item_colon' => 'Parent Group:',
    'search_items' => 'Search Groups',
    'popular_items' => 'Popular Groups',
    'separate_items_with_commas' => 'Separate Groups with commas',
    'add_or_remove_items' => 'Add or remove Groups',
    'choose_from_most_used' => 'Choose from the most used Groups',
    'not_found' => 'No Groups found',
  );
  $args = array(
    'labels'                     => $labels,
    'hierarchical'               => true,
    'public'                     => true,
    'show_ui'                    => true,
    'query_var'                  => true,
    'show_admin_column'          => true,
    'show_in_nav_menus'          => true,
    'show_tagcloud'              => false,
    'rewrite'           => array( 'slug' => 'group'),
  );
  register_taxonomy("group","community", $args);
}
add_action( 'init', 'register_taxonomy_group_community' );
// == End Script
// Start App
require get_template_directory() . '/inc/define.php';
require get_template_directory() . '/framework/init.php';
require get_template_directory() . '/inc/functions/function-setup.php';
require get_template_directory() . '/inc/functions/function-global.php';
require_once get_template_directory().'/framework/ajax/business.php';
require_once get_template_directory().'/framework/ajax/deal.php';
require_once get_template_directory().'/framework/ajax/news.php';
// End App
/**
 * Edit Post Community
 */
add_action( 'wp_ajax_edit_post_single', 'edit_post_single' );
function edit_post_single(){
  $current_user_id = get_current_user_id();
  check_ajax_referer( AT_NONCE_KEY.'edit-community'.$current_user_id, 'edit-community-token');
  $post_id = intval($_POST['post_id']);
  $content = sanitize_text_field($_POST['message']);
  $location = sanitize_text_field($_POST['location']);
  $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 = array();
  $my_post = array(
    'ID'           => $post_id,
    'post_content' => $content,
    'post_excerpt' => $location,
  );
  wp_update_post( $my_post );
  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));
    }
  }
  wp_die();
}

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

jQuery(document).ready(function($) {
  function addLoading() {
    $('#page-load').css({ 'opacity': '1', 'visibility': 'visible' });
  }
  function unLoading() {
    $('#page-load').css({ 'opacity': '0', 'visibility': 'hidden' });
  }
  const boxMessage = $('.notifi__update');
  $("body").on("submit", "form#form-update-info", function(e) {
    e.preventDefault();
    var fd = new FormData(document.getElementById("form-update-info"));
    fd.append('action', 'app_update_info');
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: fd,
      beforeSend: function() {
        addLoading()
      },
      success: function(output) {
        unLoading();
        var result = $.parseJSON(output);
        if (result.status === false) {
          setTimeout(() => {
            var currURL = window.location.href;
            var urlReload = replaceUrlParam(currURL, 'appt', 'C');
            window.location.replace(urlReload);
          }, 1500)
        } else {
          boxMessage.text(result.message);
        }
        boxMessage.removeClass('hidden');
      },
      error: function(jqXHR, textStatus, errorThrown) {
        unLoading();
        alert('error');
      }
    });
  });
  $("input").blur(function() {
    boxMessage.addClass('hidden');
  });
  $("#event-datepicker").datepicker({
    onSelect: function() {
      let dateObject = $(this).datepicker('getDate');
      $("#date").val($.datepicker.formatDate("yy-mm-dd", dateObject));
    }
  });
  $("body").on("submit", "form#form-update-post", function(e) {
    e.preventDefault();
    var fd = new FormData(document.getElementById("form-update-post"));
    fd.append('action', 'edit_post_single');
    $.ajax({
      url: app.ajaxUrl,
      type: "post",
      contentType: false,
      processData: false,
      data: fd,
      beforeSend: function() { 
        addLoading() 
      },
      success: function(output) {
        unLoading();
        var currURL = window.location.href;
        currURL = currURL.split('?')[0];
        currURL = currURL + "?appt=C";
        window.location.replace(currURL);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        unLoading();
        alert('error');
      }
    });
  });
});

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

<?php get_header();?>
<?php  
  $post_id = get_the_ID();
  $author_id = $post->post_author;
  $current_user = wp_get_current_user();
  $id_user_current = get_current_user_id();
  $is_author = false;
  $url_back = SITE_URL . '?appt=X';
  if ($author_id == $id_user_current ){
    $is_author = true;
    $url_back .= '&data=' . $post_id;
  }
?>
<div class="page-community single-community container mt-4">
  <div class="d-flex align-items-center justify-content-between action-sigle position-relative mb-4">
    <a href="<?php echo $url_back ?>" class="btn btn-bank d-flex align-items-center p-0">
      <svg width="20" height="20">
        <use href="#icon-back"></use>
      </svg>
    </a>
    <?php if ($author_id == $id_user_current) : ?>
      <div class="dropdown">
        <a class="btn" href="#" id="dropdownAction" data-bs-toggle="dropdown">
          <svg width="16" height="5">
            <use href="#icon-dots"></use>
          </svg>
        </a>
        <ul class="dropdown-menu" aria-labelledby="dropdownAction">
          <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#ModalEdit"> <?php _e('Edit post', 'umm'); ?> </a></li>
          <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#modelDeletePost"> <?php _e('Delete', 'umm'); ?> </a></li>
        </ul>
      </div>
    <?php endif ?>
  </div>
  <div class="list-posts__item" data-post-id="<?php echo $post_id; ?>">
    <div class="list-posts__item__head d-flex align-items-center justify-content-start">
        <a href="<?php echo SITE_URL ?>account?id=<?php echo $author_id; ?>&appt=N" class="d-block">
          <img src="<?php echo get_url_avatar($author_id); ?>" class="rounded-circle" width="35" height="35">
        </a>
        <div class="list-posts__item__name ml-2">
          <div class="d-flex align-items-center">
            <div class="user_name font-weight-600">
              <?php echo get_the_author_meta('display_name', $author_id); ?>
            </div>
            <div class="mx-1"> in </div>
            <div class="post_address font-weight-600">
              <?php echo wp_strip_all_tags(get_the_excerpt(), true); ?>
            </div>
          </div>
          <div class="post-date">
            <?php the_time('l, j F, Y'); ?>
          </div>
        </div>
    </div>
    <div class="list-posts__item__content mt-2">
      <?php the_content(); ?>
      <div class="box-image">
        <?php if (get_post_meta($post_id, 'img_single_community', true)) : ?>
          <?php  
            $list_images_post_arr = json_decode(get_post_meta($post_id, "img_single_community", true), true);
            $count_images = count($list_images_post_arr);
            if ($count_images == 1) {
                echo '<a href="' . get_image_url_by_id(reset($list_images_post_arr)) . '" data-fancybox>';
                echo '<img class="thumb w-100" src="' . get_image_url_by_id(reset($list_images_post_arr)) . '" /></a>';
            } else {
              echo '<div class="grid grid-cols-2">';
                foreach ($list_images_post_arr as $key => $value) {
                  echo '<a href="' . get_image_url_by_id($value) . '" data-fancybox="gallery-' . $post_id . '">';  
                  echo '<img class="thumb w-100" src="' . get_image_url_by_id($value, 'thumbnail') . '" /></a>';
                }
              echo '</div>';
            }
          ?>
        <?php endif ?>
      </div>
    </div>
  </div>
</div>
<?php if ($author_id == $id_user_current) : ?>
  <div class="page-add-post modal fade" id="ModalEdit" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
      <div class="modal-content">
        <div class="modal-header justify-content-start align-items-center">
          <button type="button" class="btn" data-bs-dismiss="modal" aria-label="Close">
            <svg width="20" height="20">
              <use href="#icon-back"></use>
            </svg>
          </button>
          <div class="font-weight-600 size-22"> <?php _e('Edit Post', 'umm'); ?> </div>
        </div>
        <div class="modal-body">
          <form id="form-update-post" class="form-add-post pb-4" action="" method="POST" enctype="multipart/form-data">
            <div class="form-group">
              <textarea class="form-control" rows="5" name="message" placeholder="<?php _e('Message', 'umm');  ?>"><?php echo get_the_content(); ?></textarea>
            </div>
            <div class="form-group">
              <input type="text" name="location" minlength="3" class="form-control location" value="<?php echo wp_strip_all_tags( get_the_excerpt(), true ); ?>" placeholder="<?php _e('Add Location', 'umm');  ?>" required autocomplete="off">
            </div>
            <div class="form-group">
              <div class="at-gr-input-file box-select-img box-preview-img d-flex align-items-center cursor">
                <img class="at-add-image-btn" src="<?php echo THEME_URL . 'images/add-img.png' ?>" width="88" height="90">
                <?php 
                    if ( isset($list_images_post_arr) && $list_images_post_arr ){
                      foreach ($list_images_post_arr as $value) {
                        echo '<div class="at-form-group">';
                          echo '<i class="fa fa-times at-remove-input remove-img" data-id-img="'.$value.'" title="Remove" aria-hidden="true"><svg width="40" height="41">';
                            echo '<use href="#icon-close"></use></svg></i>';
                          echo '<img src="'.get_image_url_by_id($value, 'thumbnail').'">';
                        echo '</div>';
                      }
                    } else {
                      echo '<div class="btn-upload p-4">'.__('Add photo', 'umm').'</div>';
                    }
                  ?>
                <div class="list_input"></div>
              </div>
            </div>
            <div class="notifi__update my-3 alert alert-warning hidden" role="alert"><?php _e('Successful', 'umm');  ?></div>
            <input type="hidden" name="list-remove-images" id="remove_image_title">
            <input type="hidden" id="remove_image" name="remove_image" value="">
            <input type="hidden" id="post_id" name="post_id" value="<?php the_ID() ?>">
            <div><?php wp_nonce_field(AT_NONCE_KEY . 'edit-community' . $id_user_current, 'edit-community-token'); ?></div>
            <button type="submit" class="btn btn__add w-100 at-rounded-14 bg-primary font-weight-500 text-white mt-3"><?php _e("Update", "umm") ?></button>
          </form>
        </div>
      </div>
    </div>
  </div>
<?php endif ?>

<?php get_footer(); ?>

Last updated