Hướng dẫn tạo một bảng upload ảnh, image (ok)
Create Post, Upload Image, Update Post && image
C:\Users\Administrator\Downloads\wp_images.sql
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 31, 2022 at 08:37 PM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.28
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `images`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_images`
--
CREATE TABLE `wp_images` (
`id` bigint(20) NOT NULL,
`image_name` varchar(255) NOT NULL,
`user_id` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `wp_images`
--
ALTER TABLE `wp_images`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `wp_images`
--
ALTER TABLE `wp_images`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
File .wpress
Create Post, Upload image
Update Post, Image 😒
C:\xampp\htdocs\images\wp-content\themes\twentytwentyone\functions.php
<?php
/**
* Functions and definitions
*
* @link https://developer.wordpress.org/themes/basics/theme-functions/
*
* @package WordPress
* @subpackage Twenty_Twenty_One
* @since Twenty Twenty-One 1.0
*/
// This theme requires WordPress 5.3 or later.
if ( version_compare( $GLOBALS['wp_version'], '5.3', '<' ) ) {
require get_template_directory() . '/inc/back-compat.php';
}
if ( ! function_exists( 'twenty_twenty_one_setup' ) ) {
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twenty_twenty_one_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on Twenty Twenty-One, use a find and replace
* to change 'twentytwentyone' to the name of your theme in all the template files.
*/
load_theme_textdomain( 'twentytwentyone', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* This theme does not use a hard-coded <title> tag in the document head,
* WordPress will provide it for us.
*/
add_theme_support( 'title-tag' );
/**
* Add post-formats support.
*/
add_theme_support(
'post-formats',
array(
'link',
'aside',
'gallery',
'image',
'quote',
'status',
'video',
'audio',
'chat',
)
);
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
*/
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 1568, 9999 );
register_nav_menus(
array(
'primary' => esc_html__( 'Primary menu', 'twentytwentyone' ),
'footer' => esc_html__( 'Secondary menu', 'twentytwentyone' ),
)
);
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support(
'html5',
array(
'comment-form',
'comment-list',
'gallery',
'caption',
'style',
'script',
'navigation-widgets',
)
);
/*
* Add support for core custom logo.
*
* @link https://codex.wordpress.org/Theme_Logo
*/
$logo_width = 300;
$logo_height = 100;
add_theme_support(
'custom-logo',
array(
'height' => $logo_height,
'width' => $logo_width,
'flex-width' => true,
'flex-height' => true,
'unlink-homepage-logo' => true,
)
);
// Add theme support for selective refresh for widgets.
add_theme_support( 'customize-selective-refresh-widgets' );
// Add support for Block Styles.
add_theme_support( 'wp-block-styles' );
// Add support for full and wide align images.
add_theme_support( 'align-wide' );
// Add support for editor styles.
add_theme_support( 'editor-styles' );
$background_color = get_theme_mod( 'background_color', 'D1E4DD' );
if ( 127 > Twenty_Twenty_One_Custom_Colors::get_relative_luminance_from_hex( $background_color ) ) {
add_theme_support( 'dark-editor-style' );
}
$editor_stylesheet_path = './assets/css/style-editor.css';
// Note, the is_IE global variable is defined by WordPress and is used
// to detect if the current browser is internet explorer.
global $is_IE;
if ( $is_IE ) {
$editor_stylesheet_path = './assets/css/ie-editor.css';
}
// Enqueue editor styles.
add_editor_style( $editor_stylesheet_path );
// Add custom editor font sizes.
add_theme_support(
'editor-font-sizes',
array(
array(
'name' => esc_html__( 'Extra small', 'twentytwentyone' ),
'shortName' => esc_html_x( 'XS', 'Font size', 'twentytwentyone' ),
'size' => 16,
'slug' => 'extra-small',
),
array(
'name' => esc_html__( 'Small', 'twentytwentyone' ),
'shortName' => esc_html_x( 'S', 'Font size', 'twentytwentyone' ),
'size' => 18,
'slug' => 'small',
),
array(
'name' => esc_html__( 'Normal', 'twentytwentyone' ),
'shortName' => esc_html_x( 'M', 'Font size', 'twentytwentyone' ),
'size' => 20,
'slug' => 'normal',
),
array(
'name' => esc_html__( 'Large', 'twentytwentyone' ),
'shortName' => esc_html_x( 'L', 'Font size', 'twentytwentyone' ),
'size' => 24,
'slug' => 'large',
),
array(
'name' => esc_html__( 'Extra large', 'twentytwentyone' ),
'shortName' => esc_html_x( 'XL', 'Font size', 'twentytwentyone' ),
'size' => 40,
'slug' => 'extra-large',
),
array(
'name' => esc_html__( 'Huge', 'twentytwentyone' ),
'shortName' => esc_html_x( 'XXL', 'Font size', 'twentytwentyone' ),
'size' => 96,
'slug' => 'huge',
),
array(
'name' => esc_html__( 'Gigantic', 'twentytwentyone' ),
'shortName' => esc_html_x( 'XXXL', 'Font size', 'twentytwentyone' ),
'size' => 144,
'slug' => 'gigantic',
),
)
);
// Custom background color.
add_theme_support(
'custom-background',
array(
'default-color' => 'd1e4dd',
)
);
// Editor color palette.
$black = '#000000';
$dark_gray = '#28303D';
$gray = '#39414D';
$green = '#D1E4DD';
$blue = '#D1DFE4';
$purple = '#D1D1E4';
$red = '#E4D1D1';
$orange = '#E4DAD1';
$yellow = '#EEEADD';
$white = '#FFFFFF';
add_theme_support(
'editor-color-palette',
array(
array(
'name' => esc_html__( 'Black', 'twentytwentyone' ),
'slug' => 'black',
'color' => $black,
),
array(
'name' => esc_html__( 'Dark gray', 'twentytwentyone' ),
'slug' => 'dark-gray',
'color' => $dark_gray,
),
array(
'name' => esc_html__( 'Gray', 'twentytwentyone' ),
'slug' => 'gray',
'color' => $gray,
),
array(
'name' => esc_html__( 'Green', 'twentytwentyone' ),
'slug' => 'green',
'color' => $green,
),
array(
'name' => esc_html__( 'Blue', 'twentytwentyone' ),
'slug' => 'blue',
'color' => $blue,
),
array(
'name' => esc_html__( 'Purple', 'twentytwentyone' ),
'slug' => 'purple',
'color' => $purple,
),
array(
'name' => esc_html__( 'Red', 'twentytwentyone' ),
'slug' => 'red',
'color' => $red,
),
array(
'name' => esc_html__( 'Orange', 'twentytwentyone' ),
'slug' => 'orange',
'color' => $orange,
),
array(
'name' => esc_html__( 'Yellow', 'twentytwentyone' ),
'slug' => 'yellow',
'color' => $yellow,
),
array(
'name' => esc_html__( 'White', 'twentytwentyone' ),
'slug' => 'white',
'color' => $white,
),
)
);
add_theme_support(
'editor-gradient-presets',
array(
array(
'name' => esc_html__( 'Purple to yellow', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $purple . ' 0%, ' . $yellow . ' 100%)',
'slug' => 'purple-to-yellow',
),
array(
'name' => esc_html__( 'Yellow to purple', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $purple . ' 100%)',
'slug' => 'yellow-to-purple',
),
array(
'name' => esc_html__( 'Green to yellow', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $green . ' 0%, ' . $yellow . ' 100%)',
'slug' => 'green-to-yellow',
),
array(
'name' => esc_html__( 'Yellow to green', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $green . ' 100%)',
'slug' => 'yellow-to-green',
),
array(
'name' => esc_html__( 'Red to yellow', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $red . ' 0%, ' . $yellow . ' 100%)',
'slug' => 'red-to-yellow',
),
array(
'name' => esc_html__( 'Yellow to red', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $yellow . ' 0%, ' . $red . ' 100%)',
'slug' => 'yellow-to-red',
),
array(
'name' => esc_html__( 'Purple to red', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $purple . ' 0%, ' . $red . ' 100%)',
'slug' => 'purple-to-red',
),
array(
'name' => esc_html__( 'Red to purple', 'twentytwentyone' ),
'gradient' => 'linear-gradient(160deg, ' . $red . ' 0%, ' . $purple . ' 100%)',
'slug' => 'red-to-purple',
),
)
);
/*
* Adds starter content to highlight the theme on fresh sites.
* This is done conditionally to avoid loading the starter content on every
* page load, as it is a one-off operation only needed once in the customizer.
*/
if ( is_customize_preview() ) {
require get_template_directory() . '/inc/starter-content.php';
add_theme_support( 'starter-content', twenty_twenty_one_get_starter_content() );
}
// Add support for responsive embedded content.
add_theme_support( 'responsive-embeds' );
// Add support for custom line height controls.
add_theme_support( 'custom-line-height' );
// Add support for experimental link color control.
add_theme_support( 'experimental-link-color' );
// Add support for experimental cover block spacing.
add_theme_support( 'custom-spacing' );
// Add support for custom units.
// This was removed in WordPress 5.6 but is still required to properly support WP 5.5.
add_theme_support( 'custom-units' );
// Remove feed icon link from legacy RSS widget.
add_filter( 'rss_widget_feed_link', '__return_false' );
}
}
add_action( 'after_setup_theme', 'twenty_twenty_one_setup' );
/**
* Register widget area.
*
* @since Twenty Twenty-One 1.0
*
* @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
*
* @return void
*/
function twenty_twenty_one_widgets_init() {
register_sidebar(
array(
'name' => esc_html__( 'Footer', 'twentytwentyone' ),
'id' => 'sidebar-1',
'description' => esc_html__( 'Add widgets here to appear in your footer.', 'twentytwentyone' ),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
)
);
}
add_action( 'widgets_init', 'twenty_twenty_one_widgets_init' );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*
* Priority 0 to make it available to lower priority callbacks.
*
* @since Twenty Twenty-One 1.0
*
* @global int $content_width Content width.
*
* @return void
*/
function twenty_twenty_one_content_width() {
// This variable is intended to be overruled from themes.
// Open WPCS issue: {@link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/1043}.
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$GLOBALS['content_width'] = apply_filters( 'twenty_twenty_one_content_width', 750 );
}
add_action( 'after_setup_theme', 'twenty_twenty_one_content_width', 0 );
/**
* Enqueue scripts and styles.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twenty_twenty_one_scripts() {
// Note, the is_IE global variable is defined by WordPress and is used
// to detect if the current browser is internet explorer.
global $is_IE, $wp_scripts;
if ( $is_IE ) {
// If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables.
wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()->get( 'Version' ) );
} else {
// If not IE, use the standard stylesheet.
wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get( 'Version' ) );
}
// RTL styles.
wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' );
// Print styles.
wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()->get( 'Version' ), 'print' );
// Threaded comment reply styles.
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
// Register the IE11 polyfill file.
wp_register_script(
'twenty-twenty-one-ie11-polyfills-asset',
get_template_directory_uri() . '/assets/js/polyfills.js',
array(),
wp_get_theme()->get( 'Version' ),
true
);
// Register the IE11 polyfill loader.
wp_register_script(
'twenty-twenty-one-ie11-polyfills',
null,
array(),
wp_get_theme()->get( 'Version' ),
true
);
wp_add_inline_script(
'twenty-twenty-one-ie11-polyfills',
wp_get_script_polyfill(
$wp_scripts,
array(
'Element.prototype.matches && Element.prototype.closest && window.NodeList && NodeList.prototype.forEach' => 'twenty-twenty-one-ie11-polyfills-asset',
)
)
);
// Main navigation scripts.
if ( has_nav_menu( 'primary' ) ) {
wp_enqueue_script(
'twenty-twenty-one-primary-navigation-script',
get_template_directory_uri() . '/assets/js/primary-navigation.js',
array( 'twenty-twenty-one-ie11-polyfills' ),
wp_get_theme()->get( 'Version' ),
true
);
}
// Responsive embeds script.
wp_enqueue_script(
'twenty-twenty-one-responsive-embeds-script',
get_template_directory_uri() . '/assets/js/responsive-embeds.js',
array( 'twenty-twenty-one-ie11-polyfills' ),
wp_get_theme()->get( 'Version' ),
true
);
}
add_action( 'wp_enqueue_scripts', 'twenty_twenty_one_scripts' );
/**
* Enqueue block editor script.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twentytwentyone_block_editor_script() {
wp_enqueue_script( 'twentytwentyone-editor', get_theme_file_uri( '/assets/js/editor.js' ), array( 'wp-blocks', 'wp-dom' ), wp_get_theme()->get( 'Version' ), true );
}
add_action( 'enqueue_block_editor_assets', 'twentytwentyone_block_editor_script' );
/**
* Fix skip link focus in IE11.
*
* This does not enqueue the script because it is tiny and because it is only for IE11,
* thus it does not warrant having an entire dedicated blocking script being loaded.
*
* @since Twenty Twenty-One 1.0
*
* @link https://git.io/vWdr2
*/
function twenty_twenty_one_skip_link_focus_fix() {
// If SCRIPT_DEBUG is defined and true, print the unminified file.
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
echo '<script>';
include get_template_directory() . '/assets/js/skip-link-focus-fix.js';
echo '</script>';
} else {
// The following is minified via `npx terser --compress --mangle -- assets/js/skip-link-focus-fix.js`.
?>
<script>
/(trident|msie)/i.test(navigator.userAgent)&&document.getElementById&&window.addEventListener&&window.addEventListener("hashchange",(function(){var t,e=location.hash.substring(1);/^[A-z0-9_-]+$/.test(e)&&(t=document.getElementById(e))&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())}),!1);
</script>
<?php
}
}
add_action( 'wp_print_footer_scripts', 'twenty_twenty_one_skip_link_focus_fix' );
/**
* Enqueue non-latin language styles.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twenty_twenty_one_non_latin_languages() {
$custom_css = twenty_twenty_one_get_non_latin_css( 'front-end' );
if ( $custom_css ) {
wp_add_inline_style( 'twenty-twenty-one-style', $custom_css );
}
}
add_action( 'wp_enqueue_scripts', 'twenty_twenty_one_non_latin_languages' );
// SVG Icons class.
require get_template_directory() . '/classes/class-twenty-twenty-one-svg-icons.php';
// Custom color classes.
require get_template_directory() . '/classes/class-twenty-twenty-one-custom-colors.php';
new Twenty_Twenty_One_Custom_Colors();
// Enhance the theme by hooking into WordPress.
require get_template_directory() . '/inc/template-functions.php';
// Menu functions and filters.
require get_template_directory() . '/inc/menu-functions.php';
// Custom template tags for the theme.
require get_template_directory() . '/inc/template-tags.php';
// Customizer additions.
require get_template_directory() . '/classes/class-twenty-twenty-one-customize.php';
new Twenty_Twenty_One_Customize();
// Block Patterns.
require get_template_directory() . '/inc/block-patterns.php';
// Block Styles.
require get_template_directory() . '/inc/block-styles.php';
// Dark Mode.
require_once get_template_directory() . '/classes/class-twenty-twenty-one-dark-mode.php';
new Twenty_Twenty_One_Dark_Mode();
/**
* Enqueue scripts for the customizer preview.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twentytwentyone_customize_preview_init() {
wp_enqueue_script(
'twentytwentyone-customize-helpers',
get_theme_file_uri( '/assets/js/customize-helpers.js' ),
array(),
wp_get_theme()->get( 'Version' ),
true
);
wp_enqueue_script(
'twentytwentyone-customize-preview',
get_theme_file_uri( '/assets/js/customize-preview.js' ),
array( 'customize-preview', 'customize-selective-refresh', 'jquery', 'twentytwentyone-customize-helpers' ),
wp_get_theme()->get( 'Version' ),
true
);
}
add_action( 'customize_preview_init', 'twentytwentyone_customize_preview_init' );
/**
* Enqueue scripts for the customizer.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twentytwentyone_customize_controls_enqueue_scripts() {
wp_enqueue_script(
'twentytwentyone-customize-helpers',
get_theme_file_uri( '/assets/js/customize-helpers.js' ),
array(),
wp_get_theme()->get( 'Version' ),
true
);
}
add_action( 'customize_controls_enqueue_scripts', 'twentytwentyone_customize_controls_enqueue_scripts' );
/**
* Calculate classes for the main <html> element.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twentytwentyone_the_html_classes() {
/**
* Filters the classes for the main <html> element.
*
* @since Twenty Twenty-One 1.0
*
* @param string The list of classes. Default empty string.
*/
$classes = apply_filters( 'twentytwentyone_html_classes', '' );
if ( ! $classes ) {
return;
}
echo 'class="' . esc_attr( $classes ) . '"';
}
/**
* Add "is-IE" class to body if the user is on Internet Explorer.
*
* @since Twenty Twenty-One 1.0
*
* @return void
*/
function twentytwentyone_add_ie_class() {
?>
<script>
if ( -1 !== navigator.userAgent.indexOf( 'MSIE' ) || -1 !== navigator.appVersion.indexOf( 'Trident/' ) ) {
document.body.classList.add( 'is-IE' );
}
</script>
<?php
}
add_action( 'wp_footer', 'twentytwentyone_add_ie_class' );
if ( ! function_exists( 'wp_get_list_item_separator' ) ) :
/**
* Retrieves the list item separator based on the locale.
*
* Added for backward compatibility to support pre-6.0.0 WordPress versions.
*
* @since 6.0.0
*/
function wp_get_list_item_separator() {
/* translators: Used between list items, there is a space after the comma. */
return __( ', ', 'twentytwentyone' );
}
endif;
// ==
add_action('wp_enqueue_scripts', 'ecademy_enqueue_style');
function ecademy_enqueue_style() {
$script_data_array = array(
'ajaxUrl' => admin_url('admin-ajax.php')
);
wp_enqueue_style("custom_css", get_stylesheet_directory_uri() . "/assets/css/custom.css", array(), '1.1.0', 'all');
wp_enqueue_script('bootstrap_js', get_stylesheet_directory_uri() . '/assets/js/bootstrap.bundle.min.js', array('jquery'), '123', 'all', true);
wp_enqueue_script('custom_js', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery'), '123', 'all', true);
wp_localize_script('custom_js', 'app', $script_data_array);
}
/**
*
* Delete uploaded images file, database
*/
function delete_img_by_id($img_id){
global $wpdb;
$table = $wpdb->prefix."images";
$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_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 . "images";
$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 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;
}
}
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 = umm_model_insert_img($fileName);
return array("status" => "success", "content" => $file_id);
}
} else {
return array("status" => "error", "content" => "Allow jpg, png, jpeg");
}
}
function umm_model_insert_img($file_name) {
global $wpdb;
$table = $wpdb->prefix . 'images';
$data = array('image_name' => $file_name, 'user_id' => get_current_user_id());
$format = array('%s', '%d');
$wpdb->insert($table, $data, $format);
return $wpdb->insert_id;
}
/**
* Add Community
*/
add_action( 'wp_ajax_app_add_community', 'app_add_community' );
function app_add_community(){
$current_user_id = get_current_user_id();
check_ajax_referer( 'add-community'.$current_user_id, 'add-community-token');
$current_list_images_post_arr = array();
$dts = $_POST['list-remove-images'];
$stt_dl = explode(',',$dts);
$post = array(
'post_title' => time(),
'post_content' => 'Content',
'post_excerpt' => "Description",
'post_status' => 'publish',
'post_type' => 'post',
);
$id_post = wp_insert_post($post);
if( !is_wp_error($id_post) ){
if ( isset($_FILES["upload_files"]) ){
for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++){
if (!in_array($i+1, $stt_dl)){
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)){
update_post_meta( $id_post, 'img_single_community', json_encode($current_list_images_post_arr));
}
}
echo "success";
}
die();
}
/**
* 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( 'edit-community'.$current_user_id, 'edit-community-token');
$post_id = intval($_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 = array();
$my_post = array(
'ID' => $post_id,
'post_content' => "Content Update",
'post_excerpt' => "Description Update",
);
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\images\wp-content\themes\twentytwentyone\page-create.php
<?php
/**
* The template for displaying all single posts
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package WordPress
* @subpackage Twenty_Twenty_One
* @since Twenty Twenty-One 1.0
*/
get_header(); ?>
<?php
$current_user_id = get_current_user_id();
?>
<div class="page-add-post add-community container">
<div class="box-add-post mt-4">
<form id="form-add-post" class="form-add-post pb-4" action="" method="POST" enctype="multipart/form-data">
<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 get_template_directory_uri() . '/assets/images/add-img.png'?>" width="88" height="90">
<div class="btn-upload p-4"> <?php _e('Add photo', 'umm'); ?> </div>
<div class="list_input"></div>
</div>
</div>
<div class="notifi__update my-3 alert alert-warning d-none" role="alert"><?php _e('Successful', 'umm'); ?></div>
<input type="hidden" name="list-remove-images" id="remove_image_title">
<div><?php wp_nonce_field('add-community' .$current_user_id, 'add-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("Post", "umm") ?></button>
</form>
</div>
</div>
<?php get_footer(); ?>
C:\xampp\htdocs\images\wp-content\themes\twentytwentyone\assets\css\custom.scss
.at_item_image {
background-color: #333;
background-position: 50%;
background-size: cover;
margin-bottom: 2px;
padding-bottom: 100%;
height: 90px;
}
.at-form-group {
margin: 5px;
height: 90px;
width: 88px;
position: relative;
}
#page-load {
-webkit-transition: 0.2s linear;
transition: 0.2s linear;
background: #fffffff7;
width: 100vw;
height: 100vh;
padding: 10px;
position: relative;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
color: #ccc;
cursor: pointer;
position: fixed;
z-index: 999999;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#page-load .loader {
width: 48px;
height: 48px;
border-radius: 50%;
display: inline-block;
border-top: 3px solid #F56B6B;
border-right: 3px solid transparent;
-webkit-animation: rotation 1s linear infinite;
animation: rotation 0.6s linear infinite;
}
@-webkit-keyframes rotation {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes rotation {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.box-image {
.grid {
display: -ms-grid;
display: grid;
-ms-grid-columns: auto auto;
grid-template-columns: auto auto;
grid-gap: 10px 10px;
-ms-flex-line-pack: center;
align-content: center;
img {
width: 100%;
}
}
}
.page-add-post .form-group .at-remove-input {
position: absolute;
background: rgba(0,0,0,0.2);
color: #fff !important;
z-index: 2;
width: 100%;
height: 100%;
text-align: center;
line-height: 22px;
cursor: pointer !important;
opacity: 1 !important;
text-shadow: none;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.at-gr-input-file {
-ms-flex-wrap: wrap;
flex-wrap: wrap;
img {
max-width: 100%;
}
}
.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;
}
C:\xampp\htdocs\images\wp-content\themes\twentytwentyone\single.php
<?php
/**
* The template for displaying all single posts
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package WordPress
* @subpackage Twenty_Twenty_One
* @since Twenty Twenty-One 1.0
*/
get_header(); ?>
<?php
$id_user_current = get_current_user_id();
?>
<div class="box-image">
<?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);
$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>
<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-' . get_the_ID() . '">
<img class="thumb w-100" src="' . get_image_url_by_id($value, 'thumbnail') . '" /></a>';
}
echo '</div>';
}
?>
<?php endif; ?>
</div>
<form id="form-update-post" class="form-add-post pb-4" action="" method="POST" enctype="multipart/form-data">
<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 get_template_directory_uri() . '/assets/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 d-none" 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('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>
<?php get_footer(); ?>
C:\xampp\htdocs\images\wp-content\themes\twentytwentyone\assets\js\custom.js
// add multiple images delete option
jQuery(document).ready(function($) {
function addLoading() {
$('#page-load').css({ 'opacity': '1', 'visibility': 'visible' });
}
function unLoading() {
$('#page-load').css({ 'opacity': '0', 'visibility': 'hidden' });
}
var xp = 0;
var input_btn = 0;
var dts = [];
var l = $(".at-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) {
let leg_current = $(".at-gr-input-file .at-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) {
$('.btn-upload').addClass('hidden');
let leg_current = $(".at-gr-input-file .at-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;
$(".at-gr-input-file").append(
"<div class='at-form-group at-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'><svg width='40' height='41'><use href='#icon-close'></use></svg></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(".at-form-group").remove();
$('#remove_image_title').val(dts);
});
// delete image update post
var arr_img_delete = [];
$(".single").on("click", ".remove-img", function(e) {
var data_id = $(this).data('id-img');
arr_img_delete.push(data_id);
$(this).parent(".at-form-group").remove();
$('#remove_image').val(arr_img_delete);
});
const boxMessage = $('.notifi__update');
$("body").on("submit", "form#form-add-post", function(e) {
e.preventDefault();
var fd = new FormData(document.getElementById("form-add-post"));
fd.append('action', 'app_add_community');
$.ajax({
url: app.ajaxUrl,
type: "post",
contentType: false,
processData: false,
data: fd,
beforeSend: function() { addLoading() },
success: function(output) {
unLoading();
boxMessage.removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
unLoading();
}
});
});
$("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();
},
error: function(jqXHR, textStatus, errorThrown) {
unLoading();
alert('error');
}
});
});
});
C:\xampp\htdocs\images\wp-content\themes\twentytwentyone\header.php
<?php
/**
* The header.
*
* This is the template that displays all of the <head> section and everything up until main.
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package WordPress
* @subpackage Twenty_Twenty_One
* @since Twenty Twenty-One 1.0
*/
?>
<!doctype html>
<html <?php language_attributes(); ?> <?php twentytwentyone_the_html_classes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css"/>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page-load" style="opacity: 0; visibility: hidden;"><span class="loader"> </span></div>
<?php wp_body_open(); ?>
<div id="page" class="site">
<a class="skip-link screen-reader-text" href="#content"><?php esc_html_e( 'Skip to content', 'twentytwentyone' ); ?></a>
<?php get_template_part( 'template-parts/header/site-header' ); ?>
<div id="content" class="site-content">
<div id="primary" class="content-area">
<main id="main" class="site-main">
Previous[FRAMEWORK] Xây dựng page notifications Phần 2 (ok)NextTích hợp framework vô wordpress phần 2 (ok)
Last updated
Was this helpful?