Tổng hợp 1 số code chèn vào functions.php

functions.php

1. Ẩn Menu trong Admin Menu

function remove_menus(){ 
remove_menu_page( 'index.php' ); //Dashboard
remove_menu_page( 'edit.php' ); //Posts
remove_menu_page( 'upload.php' ); //Media
remove_menu_page( 'edit.php?post_type=page' ); //Pages
remove_menu_page( 'edit-comments.php' ); //Comments
remove_menu_page( 'themes.php' ); //Appearance
remove_menu_page( 'plugins.php' ); //Plugins
remove_menu_page( 'users.php' ); //Users
remove_menu_page( 'tools.php' ); //Tools
remove_menu_page( 'options-general.php' ); //Settings 
}
add_action( 'admin_menu', 'remove_menus' );

2. Chế độ bảo trì nhanh

function hdev_che_do_bao_tri()
{
    if (!current_user_can(‘edit_themes’) || !is_user_logged_in()) {
        wp_die(‘Trang web tạm thời đang được bảo trì. Xin vui lòng quay trở lại sau.’);
    }
}
add_action(‘get_header’, ‘hdev_che_do_bao_tri’);

3. Vô hiệu hóa WooCommerce Admin

add_filter( 'woocommerce_admin_disabled', '__return_true' );

4. Thêm font đuôi .woff vào upload

function my_myme_types($mime_types){
    $mime_types['woff'] = 'application/x-font-woff';
    return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);

5. Bật Classic Editor

add_filter('use_block_editor_for_post', '__return_false');

6. Bật Classic Widgets

add_filter( 'gutenberg_use_widgets_block_editor', '__return_false' );
add_filter( 'use_widgets_block_editor', '__return_false' );

7. Dịch nhanh Woocommerce

add_filter( 'gettext', 'huanle_translate_woocommerce_strings', 999 );
function huanle_translate_woocommerce_strings( $translated ) {
    $translated = str_ireplace( 'Đọc tiếp', 'Xem thêm', $translated );
    return $translated;
}

8. Check SĐT hợp lệ Contact Form 7

function custom_filter_wpcf7_is_tel( $result, $tel ) { 
  $result = preg_match( '/((09|03|07|08|05)+([0-9]{8})\b)/', $tel );
  return $result; 
}
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );

hoặc (OK)

function tmdev_validate_phone_vietnam( $result, $tag ) {
$name = $tag->name;
$value = isset( $_POST[$name] ) ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) ) : '';
$errorMessage = 'Số điện thoại không hợp lệ!';
if ( 'tel' == $tag->basetype ) {
if( !preg_match('/^(03|05|07|08|09)+[0-9]{8}$/', $value ) ){
$result->invalidate( $tag, $errorMessage );
}
}
return $result;
}
add_filter('wpcf7_validate_tel*', 'tmdev_validate_phone_vietnam', 10, 2);

hoặc

/* Kiểm tra số điện thoại có 10 số của Việt Nam */
function custom_filter_wpcf7_is_tel( $result, $tel ) { 
  $result = preg_match( '/^(0|\+84)(\s|\.)?((3[2-9])|(5[689])|(7[06-9])|(8[1-689])|(9[0-46-9]))(\d)(\s|\.)?(\d{3})(\s|\.)?(\d{3})$/', $tel );
  return $result; 
}
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );

hoặc

add_filter( 'wpcf7_validate_tel*', function ( $result, $tag ) {
 if ( 'your-phone' == $tag->name ) {
  $phone = isset( $_POST['your-phone'] ) ? trim( $_POST['your-phone'] ) : '';
  if(!preg_match( '/^(09|03|07|08|05)+([0-9]{8})$/', $phone )){
   $result->invalidate( $tag, "Số điện thoại không đúng!" );
  }
 }
 return $result;
}, 20, 2 );

9. Cấu hình SMTP

add_action( 'phpmailer_init', function( $phpmailer ) {
    if ( !is_object( $phpmailer ) )
    $phpmailer = (object) $phpmailer;
    $phpmailer->Mailer     = 'smtp';
    $phpmailer->Host       = 'smtp.gmail.com';
    $phpmailer->SMTPAuth   = 1;
    $phpmailer->Port       = 587;
    $phpmailer->Username   = '[email protected]'; // Tài khoản gmail
    $phpmailer->Password   = 'yiovemykuxrszvpw'; // Mật khẩu ứng dụng
    $phpmailer->SMTPSecure = 'TLS';
    $phpmailer->From       = '[email protected]'; // Tài khoản gmail gửi mail
    $phpmailer->FromName   = 'HuanLe Media'; // Tên tài khoản gửi mail
});

hoặc tham khảo

function setup_smtp_email() {
    if ( ! class_exists( 'PHPMailer\PHPMailer\PHPMailer' ) ) {
        require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
        require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
        require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
    }
    $mailer = new PHPMailer\PHPMailer\PHPMailer( true );
    $mailer->isSMTP();
    $mailer->Host       = 'smtp.gmail.com';
    $mailer->SMTPAuth   = true;
    $mailer->Port       = 587;
    $mailer->Username   = 'email nhập vào';
    $mailer->Password   = 'pass app';
    $mailer->SMTPSecure = 'tls';
    $mailer->From       = 'email nhập vào ';
    $mailer->FromName   = 'Gửi từ website SEX';
    add_action( 'phpmailer_init', function( $phpmailer ) use ( $mailer ) {
        $phpmailer = $mailer;
    });
}
add_action( 'init', 'setup_smtp_email' );

10. Thêm nội dung trước bài post

function mh_before($content) {
    $beforecontent = 'Nội dung cần chèn'; // Sửa chỗ này
    fullcontent = $beforecontent . $content;
    return $fullcontent;
}
add_filter('the_content', 'mh_before');

11. Thêm nội dung cuối bài post

function mh_after($content) {
    $aftercontent = 'Nội dung cần chèn'; //Sửa chỗ này
    $fullcontent = $content . $aftercontent;
    return $fullcontent;
}
add_filter('the_content', 'mhafter');

12. Thêm nội dung vào cả trước và sau bài post

function mh_before_after($content) {
    $beforecontent = 'Nội dung trước bài viết';
    $aftercontent = 'Nội dung sau/cuối bài viết';
    $fullcontent = $beforecontent . $content . $aftercontent;
   
    return $fullcontent;
}
add_filter('the_content', 'mh_before_after');

13. Ẩn Header Woocommerce trong Admin

/* Hide WooCommerce Breadcrumb */ 
add_action('admin_head', 'huanlt_reg_style_back'); 
function huanlt_reg_style_back() 
{ 
?> 
    <style>.woocommerce-layout__header.is-scrolled {display: none;}</style> 
<?php 
}

hoặc

/* Remove Admin Head WooCommerce */ 
add_action('admin_head', 'my_custom_css'); 
function my_custom_css() { 
  echo '<style>.woocommerce-layout__header-wrapper{display: none !important;}</style>'; 
}

14. Xóa ảnh đi kèm khi xóa bài viết

function delete_post_attachments($post_id) {
    global $wpdb;
    $sql = "SELECT ID FROM $wpdb->posts";
    $sql .= " WHERE post_parent = ".$post_id;
    $sql .= " AND post_type = 'attachment'";

    $ids = $wpdb->get_results($sql);
    foreach ( $ids as $id ) {
        wp_delete_attachment($id->ID, true);
    }
}
add_action('before_delete_post', 'delete_post_attachments');

15. Change WooCommerce "Related products" text

add_filter('gettext', 'change_rp_text', 10, 3);
add_filter('ngettext', 'change_rp_text', 10, 3);

function change_rp_text($translated, $text, $domain)
{
     if ($text === 'Related products' && $domain === 'woocommerce') {
         $translated = esc_html__('Viết cái gì thì viết', $domain);
     }
     return $translated;
}

16. Chặn Gutenberg

/* Chặn Gutenberg */
add_filter('use_block_editor_for_post_type', '__return_false', 10);
/* Chặn load các css liên quan đến Gutenberg của wordpress  */
wp_dequeue_style( 'wp-block-library' );
/* Chặn load các css liên quan hỗ trợ theme liên quan đến Gutenberg */
wp_dequeue_style( 'wp-block-library-theme' );
/* Chặn load các css liên của woo liên quan đến Gutenberg */
wp_dequeue_style( 'wc-block-style' );

17. Code html đơn giản

<a href="#" onClick="alert('Module đang cập nhật');return false"><span>Chính sách bán hàng</span></a>

18. Javascript Ngày tháng đơn giản

/* Ngày tháng đơn giản */
<script type="text/javascript" type="text/javascript"> 
         var mydate=new Date()
         var year=mydate.getYear()
         if (year < 1000)
         year+=1900
         var day=mydate.getDay()
         var month=mydate.getMonth()
         var daym=mydate.getDate()
         if (daym<10)
         daym="0"+daym
         var dayarray=new Array("Chủ nhật","Thứ hai","Thứ ba","Thứ tư","Thứ năm","Thứ sáu","Thứ bảy")
         var montharray=new Array("01","02","03","04","05","06","07","08","09","10","11","12")
         document.write(""+dayarray[day]+", ngày "+daym+"/"+montharray[month]+"/"+year+"")
        </SCRIPT>

19. Trang trí tết đơn giản

function tet2024(){;?>
<style type='text/css'>
        .tet_left img, .tet_right img {
            width: 100%;
            height: auto;
        }
        .tet_left, .tet_right {
            position: fixed;
            top: 0;
            left: 0;
            z-index: 9999;
            width: 145px;
            pointer-events: none;
        }
        .tet_right {
            left: auto;
            right: 0;
            width: 145px;
        }

        @media (max-width: 1285px){
            .tet_left, .tet_right{
                display: none !important;
            }
        }
    </style>
<div class="tet_left"><img src="https://i.imgur.com/PWAYyza.png" alt="Giáp Thìn"/></div>        
<div class="tet_right"><img src="https://i.imgur.com/s2SuyZA.png" alt="2024"/></div>                    
        
<?php }
add_action('wp_footer','tet2024');

20. Thu gọn biến thể woocomerce (khi có quá nhiều sẽ ẩn bớt và hiện chữ More)

function thugon_xem_them_bien_the(){ 
?> 
<script> 
document.addEventListener('DOMContentLoaded', function() { 
var chon_swatches = document.querySelectorAll('.ux-swatches'); 
chon_swatches.forEach(function(chon_swatches_con) { 
var swatches = chon_swatches_con.querySelectorAll('.ux-swatch'); 
if (swatches.length > 3) { 
for (var i = 3; i < swatches.length; i++) { 
swatches[i].classList.add('hidden'); 
} 
var nutxemthem = document.createElement('div'); 
nutxemthem.textContent = 'More'; 
nutxemthem.classList.add('show-more-btn'); 
nutxemthem.style.cursor = 'pointer';  
chon_swatches_con.appendChild(nutxemthem); 
nutxemthem.addEventListener('click', function(event) { 
event.stopPropagation(); 
for (var i = 3; i < swatches.length; i++) { 
swatches[i].classList.toggle('hidden'); 
} 
this.textContent = (this.textContent === 'More') ? 'Less' : 'More'; 
}); 
} 
}); 
}); 
</script> 
<?php 
} 
add_action('wp_footer','thugon_xem_them_bien_the');

21. Đổi vị trí giá biến thể lên trên bên dưới tiêu đề

add_action( 'wp_footer', 'hien_gia_bien_the_duoi_tieu_de', 25 ); 
function hien_gia_bien_the_duoi_tieu_de() { 
?> 
<script type="text/javascript"> 
jQuery(document).ready(function ($) { 
jQuery(document).ready(function(event) { 
var m = $('.price.product-page-price').html(); 
jQuery('.single_variation_wrap').change(function(){ 
$('.woocommerce-variation-price').hide(); 
var p = $('.single_variation_wrap').find('.price').html(); 
$('.price.product-page-price').html(p); 
}); 
jQuery('body').on('click','.reset_variations',function(event) { 
$('.price.product-page-price').html(m); 
}); 
}); 
}); 
</script>  
<?php 
}

22. Tăng bộ nhớ cho Theme bằng file Config.php

define( 'WP_MEMORY_LIMIT', '256M' );

23. Tham khảo Menu Phở bát đá cũ

.isures-prod--item {display: flex;align-items: center;padding: 10px 0;}
.isures-prod--image {max-width: 80px;flex-basis: 80px;width: 100%;margin-right: 10px;-webkit-transform: scale(1);transform: scale(1);-webkit-transition: .6s ease-in-out;transition: .6s ease-in-out;}
.isures-prod--image:hover img {-webkit-transform: scale(1.2);transform: scale(1.2);}
.isures-prod--image img {border-radius: 50%;}
.isures-content--prod_wrap {flex-basis: calc(100% - 90px);}
.isures-content--prod_top {display: flex;justify-content: space-between;align-items: flex-end;}
.isures-prod--line {position: relative;-webkit-flex: 100 0 auto;flex: 100 0 auto;border-top: 1px solid #d8d8d8;margin-left: 10px;margin-right: 10px;margin-bottom: 7px;}
.isures-prod--title {font-size: 16px;color: #1d1d1d;text-transform: uppercase;}
.isures-prod--price .amount {font-weight: normal;font-size: 16px;color: var(--primary-color);}
.isures-content--prod_bottom {font-size: 12px;color: #676767;text-align: left;}

<div class="isures-prod--item">
<div class="isures-prod--image"><img src="/wp-content/uploads/2021/07/pbd37-menu.jpg" width="150" height="150" /></div>
<div class="isures-content--prod_wrap">
<div class="isures-content--prod_top">
<div class="isures-prod--title">Phở bò tái</div>
<div class="isures-prod--line"></div>
<div class="isures-prod--price"><span class="woocommerce-Price-amount amount"><bdi>65.000<span class="woocommerce-Price-currencySymbol">₫/bát</span></bdi></span></div>
</div>
</div>
</div>

24. Chữ ký Gmail for sale

<table style="border: 0px">
<tbody>
<tr>
<td><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfIW2TANp8Kur2XsEjECPlWVhLzWj5IiiMEX_hB72IE-bWda9Jj-nuONthkwKO48xRCQDjR2MYrpJjWneK6yNyJPPMBImQ4fKQl7RwLMS2E1IYx4JLoW6ZGAEAg_64L0K_97thh_OzXtZHnk9jvShZqxcNJ6PkP3cnotJCurGJ6dAJKsHnj8dd5jzQDQWO/s1600/logo-tiec37-100.jpg"></td>
<td><span style="font-weight:bold;">Ms. DOE</span><br>
<span style="font-weight:700"><em>Sales</em></span><br>
Hotline:&nbsp;<a href="tel:0888319866" target="_blank">0888.31.9866</a><br>
Email:&nbsp;<a href="mailto:[email protected]" target="_blank">[email protected]</a><br>
Website:&nbsp;<a href="https://tiec37.vn/" target="_blank">https://tiec37.vn</a><br>
Fanpage:&nbsp;<a href="https://facebook.com/tiec37/" target="_blank">https://facebook.com/tiec37/</a></td>
</tr>
</tbody>
</table>

25. Xóa toàn bộ sản phẩm có trong Woo

Code chạy bằng link /wp-admin/?delete_all_products=true

function delete_all_products() {
    if (!current_user_can('administrator')) {
        return;
    }
    // Check for a specific user action to trigger the product deletion
    if (isset($_GET['delete_all_products']) && $_GET['delete_all_products'] == 'true') {
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'any'
        );
        $products = get_posts($args);
        foreach ($products as $product) {
            wp_delete_post($product->ID, true);
        }
        echo 'All products have been deleted.';
    }
}

add_action('admin_init', 'delete_all_products');
add_action( 'before_delete_post', 'delete_all_attached_media' );
function delete_all_attached_media( $post_id ) {
if( get_post_type($post_id) == "product" ) {
$attachments = get_attached_media( '', $post_id );
foreach ($attachments as $attachment) {
wp_delete_attachment( $attachment->ID, 'true' );
}
}
}

26. Tắt thông báo bản quyền theme Flatsome

/* Remove Flatsome Notice */
add_action('init', 'hide_notice');
function hide_notice() {
    remove_action('admin_notices', 'flatsome_maintenance_admin_notice');}

27. Ẩn khung chọn Ngôn ngữ khi login admin Wordpress

/* Hide Language Switcher */
add_filter( 'login_display_language_dropdown', '__return_false' );

28. Override folder INC cho theme Flatsome

/* override folder INC cho blog */
function vdh_override_shortcodes()
{
    require get_stylesheet_directory() . '/inc/shortcodes/blog_posts.php';
    // Thêm file tương tự cần sửa vào đây
}
add_action('wp_loaded', 'vdh_override_shortcodes', 10);

29. Giữ nguyên chất lượng ảnh khi up lên Wordpress

add_filter('jpeg_quality', function($arg){return 100;});

30. Loại bỏ các kích thước ảnh mặc định trong WordPress

function remove_default_image_sizes( $sizes ) {
  $sizes_to_remove = array(
   'large', 'thumbnail', 'medium', 'medium_large', 'woocommerce_thumbnail', 'woocommerce_single',
   'woocommerce_gallery_thumbnail', '1536x1536', '2048x2048', '360x180', '150x150', '150x133',
   '768x0', '0x0', '750x375', '1140x570', '750x536', '1140x815', '360x504', '75x75',
   '100x100', '300x300', '600x338'
  );
  foreach ( $sizes_to_remove as $size ) {
   unset( $sizes[ $size ] );
  }
  return $sizes;
 }
 add_filter( 'intermediate_image_sizes_advanced', 'remove_default_image_sizes' );

31. Bỏ mục email trong phần thanh toán Woo

function wc_remove_checkout_fields($fields)
{
    $fields['billing']['billing_email']['required'] =  false;
    return $fields;
}
add_filter('woocommerce_checkout_fields', 'wc_remove_checkout_fields');

32. Hiện giá sale và tiết kiệm %

function custom_price_loop_display($price_html, $product) {
    if ($product->is_on_sale()) {
        $regular_price = $product->get_regular_price();
        $sale_price = $product->get_sale_price();
        $savings_amount = wc_price($regular_price - $sale_price);
        $price_html = '<span class="devvn_single_price">
            <span class="devvn_price">From ' . wc_price($sale_price) . '</span>
            <span class="devvn_price"><del>' . wc_price($regular_price) . '</del></span>
            <span class="devvn_price">Save ' . $savings_amount . '</span>
        </span>';
    }
    return $price_html;
}

add_filter('woocommerce_get_price_html', 'custom_price_loop_display', 10, 2);

33. Tracking nguồn người dùng contact form 7 qua email

Sử dụng shortcode [tracking-info] trong form

// Add the info to the email
function wpshore_wpcf7_before_send_mail($array) {
	global $wpdb;
	if(wpautop($array['body']) == $array['body']) // The email is of HTML type
		$lineBreak = "<br/>";
	else
		$lineBreak = "\n";
	$trackingInfo .= $lineBreak . $lineBreak . '-- Tracking Info --' . $lineBreak;
	$trackingInfo .= 'URL điền form: ' . $_SERVER['HTTP_REFERER'] . $lineBreak;
	if (isset ($_SESSION['OriginalRef']) )
		$trackingInfo .= 'Người dùng đến từ trang: ' . $_SESSION['OriginalRef'] . $lineBreak;
	if (isset ($_SESSION['LandingPage']) )
		$trackingInfo .= 'Trang đích trước khi điền form: ' . $_SESSION['LandingPage'] . $lineBreak;
	if ( isset ($_SERVER["REMOTE_ADDR"]) )
	$trackingInfo .= 'IP người dùng: ' . $_SERVER["REMOTE_ADDR"] . $lineBreak;
	if ( isset ($_SERVER["HTTP_X_FORWARDED_FOR"]))
		$trackingInfo .= 'User\'s Proxy Server IP: ' . $_SERVER["HTTP_X_FORWARDED_FOR"] . $lineBreak . $lineBreak;
	if ( isset ($_SERVER["HTTP_USER_AGENT"]) )
		$trackingInfo .= 'Thông tin trình duyệt: ' . $_SERVER["HTTP_USER_AGENT"] . $lineBreak;
	$array['body'] = str_replace('[tracking-info]', $trackingInfo, $array['body']);
    return $array;
}
add_filter('wpcf7_mail_components', 'wpshore_wpcf7_before_send_mail');
// Original Referrer 
function wpshore_set_session_values() 
{
	if (!session_id()) 
	{
		session_start();
	}
	if (!isset($_SESSION['OriginalRef'])) 
	{
		$_SESSION['OriginalRef'] = $_SERVER['HTTP_REFERER']; 
	}
	if (!isset($_SESSION['LandingPage'])) 
	{
		$_SESSION['LandingPage'] = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; 
	}
}
add_action('init', 'wpshore_set_session_values');

34. Countdown timer trong Flatsome tự động reset thời gian

function itseovn_auto_countdown($args, $content)
{
    $date = new DateTime();
    date_modify($date,"+2 days");
    $date_add = date_format($date,"Y-m-d");
    $year = date('Y', strtotime($date_add));
    $month = date('m', strtotime($date_add));
    $day = date('d', strtotime($date_add));

    $contents = do_shortcode('<div id="timer-745813216" class="ux-timer dark" data-text-plural="s" data-text-hour="Giờ" data-text-day="Ngày" data-text-week="Tuần" data-text-min="Phút" data-text-sec="Giây" data-text-hour-p="Giờ" data-text-day-p="Ngày" data-text-week-p="Tuần" data-text-min-p="Phút" data-text-sec-p="Giây" data-countdown="' . $year . '/' . $month . '/' . $day . ' 00:00"><span> <div class="loading-spin dark centered"></div><strong> </strong></span></div>
<style>
#timer-745813216 {
  font-size: 300%;
}
</style>
');
    return $contents;
}
add_shortcode( 'shortcode_itseovn_auto_countdown', 'itseovn_auto_countdown' );

Thêm vào vị trí cần hiển thị gọi shortcode đó ra: [shortcode_itseovn_auto_countdown]


35. Fake đánh giá với plugin kk Star Ratings

function update_post_kk(){
    $a = get_posts(array(
        'post_type'      => 'post',
        'fields'          => 'ids',
        'posts_per_page'  => -1
    ));
    foreach ($a as $id){
        $count = rand(94, 100);
        $count2 = rand(460, 490);
        update_post_meta( $id, '_kksr_ratings', $count2 );
        update_post_meta( $id, '_kksr_casts', $count );
        update_post_meta( $id, '_kksr_ratings_default', $count2 );
        update_post_meta( $id, '_kksr_count_default', $count );
    }
}
add_action('init','update_post_kk');

Giải thích 1 chút

  • Chỗ post_type thay thành page hoặc product để đánh giá cho trang hoặc sản phẩm
  • Chỗ posts_per_page để -1 là đánh giá tất cả, 1 là đánh giá bài mới nhất.
  • Thay cái chỗ count là số lượng đánh ngẫu nhiên từ 94-100
  • Thay chỗ count2 là số sao trung bình: lấy số trong count2 chia cho số trong count.

36. Thêm Font Awesome cho website WordPress

function st_load_fontawesome() {
     wp_enqueue_style('font-awesome', 'https://cdn.jsdelivr.net/npm/@fortawesome/[email protected]/css/all.min.css');
}
add_action('wp_enqueue_scripts','st_load_fontawesome');

37. Vô hiệu chức năng chỉnh sửa file trong Admin Dashboard

// Disable file editor in WP admin dashboard
define('DISALLOW_FILE_EDIT', true);

Ngoài ra, để vô hiệu chức năng cài đặt hoặc thay đổi Plugins hoặc Themes thì có thể thêm dòng này:

define('DISALLOW_FILE_MODS', true);

38. Hiển thị gallery của sản phẩm ra bên ngoài sản phẩm

add_action('wp_footer','isures_add_script_footer');
 
function isures_add_script_footer(){
?>
<script>
jQuery('body').on('mouseenter', '.isures-thumb--items', function () {
 
        let change_box = jQuery(this).closest('.product-small');
        let img_this = jQuery(this).find('img').attr('data-full');
        jQuery(change_box).find('.box-image img').attr('src', img_this);
        jQuery(change_box).find('.box-image img').attr('srcset', img_this);
        jQuery(change_box).find('.isures-thumb--items').removeClass('active');
        jQuery(this).addClass('active');
    });
 
</script>
<style>
.product-small.col > .col-inner {
padding-bottom: 60px;
border: 1px solid #f5f5f5;
border-radius: 5px;
background: #fff;
box-shadow: 0 3px 11px rgb(0 0 0 / 7%);
}
.isures-thumb--wrap {
position: absolute;
bottom: 0;
display: flex;
}
.isures-thumb--items{
max-width: calc(25% - 4px);
width: 100%;
margin-right: 5px;
cursor: pointer;
}
.isures-thumb--items:nth-child(4){
margin-right: 0
}
.isures-thumb--items.active{
border: 1px solid var(--isures-primary-color)
}
.isures-thumb--items img {
border: 1px solid transparent
}
.isures-more--btn {
position: absolute;
right: 0;
bottom: 0;
width: 25%;
height: 100%;
background: rgba(0,0,0, .54);
color: #fff!important;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.isures-more--btn span{
font-size: 10px;
text-align: center; 
font-weight: bold;
}
</style>
<?php
}

39. Thông tin liên hệ quản trị website

/* Thông tin liên hệ quản trị website */
function create_widget_notice()
{
	wp_add_dashboard_widget('realdev_notice', 'Hotline Hỗ Trợ', 'realdev_notice_callback');
}
add_action('wp_dashboard_setup', 'create_widget_notice');

function realdev_notice_callback()
{
?>
	<div class="realdev-support">
		<h2 class="title">Các Kênh Hỗ Trợ</h2>
		<p>Xin chào Quý Khách. Chúng tôi sẵn sàng hỗ trợ mọi phát sinh liên quan đến Source Code hoặc các phần chúng tôi đã cam kết. Đừng ngại liên hệ với chúng tôi</p>
		<ul>
			<li class="hotline"><a href="tel:0987127039" target="_blank" rel="noopener noreferrer"><span class="lable">Hotline</span> <span class="value">0987.127.039</span></a></li>
			<li class="zalo"><a href="https://zalo.me/0987127039" target="_blank" rel="noopener noreferrer"><span class="lable">Zalo</span> <span class="value">0987.127.039</span></a></li>
			<li class="website"><a href="https://huanlt.com/" target="_blank" rel="noopener noreferrer"><span class="lable">Website</span> <span class="value">huanlt.com</span></a></li>
		</ul>
	</div>
	<style>
		.realdev-support {
			text-align: center;
		}

		.realdev-support p {
			font-size: 15px;
		}

		.realdev-support ul {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			justify-content: space-between;
		}

		.realdev-support li {
			flex: 1;
			margin: 5px;
		}

		.realdev-support a {
			background: #2271b1;
			color: #fff;
			padding: 10px 20px;
			border-radius: 5px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}

		.realdev-support a .value {
			font-size: 18px;
			font-weight: bold;
		}

		.realdev-support a:hover {
			background: orange;
		}
	</style>
<?php
}

40. Tạo mã QR rồi thêm vào dưới cuối bài viết

/* Tạo mã QR cho từng bài viết */
function maqr($content) {
if(is_singular()) {
ob_start();
?>
<div style="text-align:center">
<img src="http://api.qrserver.com/v1/create-qr-code/?size=64x64&data=<?php the_permalink(); ?>" alt="QR: <?php the_title(); ?>"/>
</div>
<?php
$hienqr = ob_get_clean();
return $content . $hienqr;
} else {
return $content;
}
}
add_filter( 'the_content', 'maqr');

41. Nút liên hệ chạy bên web đơn giản

function custom_contact(){;?>
<style type='text/css'>
#icon-fixed-right {
    width: 50px;
    position: fixed;
    right: 5px;
    top: 250px;
    z-index: 997;
}
#icon-fixed-right a:first-child {
    margin-top: 0;
}
#icon-fixed-right a {
    display: block;
    margin-top: 5px;
	padding-top: 5px;
}
#icon-fixed-right img:hover {-webkit-transform: scale(1.1);transform: scale(1.1);}
</style>
<div id="icon-fixed-right">
	<a href="https://www.facebook.com/lehuan0710" target="_blank"><img src="/wp-content/uploads/2024/10/facebook_logo_icon.png" alt="Facebook"></a>
	<a href="https://www.instagram.com/lehuan.media/" target="_blank"><img src="/wp-content/uploads/2024/10/icon-insta.png" alt="Instagram"></a>
    <a href="https://www.tiktok.com/@huanlt" target="_blank"><img src="/wp-content/uploads/2024/10/icon-tiktok.png" alt="Tiktok"></a>
	<a href="https://www.youtube.com/@lehuanmedia" target="_blank"><img src="/wp-content/uploads/2024/10/youtube.png" alt="Youtube"></a>
	<a href="https://zalo.me/0987127039" target="_blank"><img src="/wp-content/uploads/2024/10/zalo.png" alt="Zalo"></a>
</div><?php }
add_action('wp_footer','custom_contact');

42. Bài viết liên quan (không ảnh) cho theme Flatsome

//code bài viết liên quan theme flatsome
function flatsome_related_post($content) {
    if(is_singular('post')) {
        global $post;
        ob_start();
     ?>
<style>
	.xem-them {
	padding: 8px 35px 8px 14px;
    margin: 20px 0;
    text-shadow: 0 1px 0 rgba(255, 255, 255, .5);
    border: 1px solid #bce8f1;
    border-radius: 4px;
    background-color: #d9edf7;
	}	
	.xem-them .tieu-de-xem-them {
    font-weight: 700;
    display: block;
    margin-bottom: 10px;
    font-size: 19px;
	}
	.xem-them ul li {
	list-style-image: url(/wp-content/uploads/2024/10/star.gif);
	}
</style>
<?php
$categories = get_the_category(get_the_ID());
if ($categories){
    echo '<div class="xem-them">';
    $category_ids = array();
    foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    $args=array(
        'category__in' => $category_ids,
        'post__not_in' => array(get_the_ID()),
        'posts_per_page' => 5, // So bai viet dc hien thi
        'orderby' => 'rand',
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() ):
        echo '<span class="tieu-de-xem-them">Xem thêm:</span>
        <ul>';
        while ($my_query->have_posts()):$my_query->the_post();
            ?>
            <li>
             <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
            </li>
            <?php
        endwhile;
        echo '</ul>';
    endif; wp_reset_query();
    echo '</div>';
}
        $related_post = ob_get_contents();
        ob_end_clean();
        return $content.$related_post;
    } //end if is single post
    else return $content;
}
add_filter('the_content', 'flatsome_related_post');

43. Code html random Zalo

<ul>
<li><a href="javascript:;" onclick="randomlinkZL()"></a></li>
</ul>

<script>
var randomlinkzalo=new Array()
randomlinkzalo[1]="https://zalo.me/0987127039"
randomlinkzalo[2]="https://zalo.me/0936685088"

function randomlinkZL() {
window.location=randomlinkzalo[Math.floor(Math.random()*randomlinkzalo.length)]
}
</script>

44. Rút ngắn tiêu đề bài viết & sản phẩm

/* Function rút ngắn title của bài post */
add_filter( 'the_title', 'shorten_post_title', 10, 2 );
function shorten_post_title( $title, $id ) {
    if (get_post_type( $id ) === 'post' &amp; !is_single() ) {
        return wp_trim_words( $title, 14 ); // thay đổi số từ bạn muốn hiển thị
    } else {
        return $title;
    }
}

/* Function rút ngắn title sản phẩm */
add_filter( 'the_title', 'short_title_product', 10, 2 );
function short_title_product( $title, $id ) {
    if (get_post_type( $id ) === 'product' &amp; !is_single() ) {
        return wp_trim_words( $title, 7 ); // thay đổi số từ bạn muốn thêm
    } else {
        return $title;
    }
}

45. Add the add to cart

/* Add the add to cart */
add_filter('woocommerce_product_single_add_to_cart_text', 'sm_woo_custom_cart_button_text');
add_filter('woocommerce_product_add_to_cart_text', 'sm_woo_custom_cart_button_text');

function sm_woo_custom_cart_button_text(){
          return __('Mua ngay', 'woocommerce');
}

46. Thêm facebook comment cho cả bài viết & sản phẩm

/* Thêm Facebook JavaScript SDK */
add_action('wp_head', 'fb_javascript_sdk');
function fb_javascript_sdk() {
    ?>
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v6.0&appId=2354141998011632&autoLogAppEvents=1"></script>
    <?php
}
// Thêm facebook comment cho cả bài viết & sản phẩm
function mh_add_product_content($content) {
    if (is_single() && !is_404()) {
      $content .= '<div class="fb-like" data-href="" data-width="" data-layout="button_count" data-action="like" data-size="small" data-share="true"></div>';
    }
    return $content;
}
add_filter ('the_content', 'mh_add_product_content', 0);

47. Dịch tiếng Việt nhanh 1 số cụm từ thường gặp

/* Dich Tieng Viet */
function ra_change_translate_text( $translated_text ) {
if ( $translated_text == 'Old Text' ) {
$translated_text = 'New Translation';
}
return $translated_text;
}
add_filter( 'gettext', 'ra_change_translate_text', 20 );
function ra_change_translate_text_multiple( $translated ) {
$text = array(
'Mô tả' => 'Mô tả sản phẩm',
'Quick View' => 'Xem nhanh',
'Oops! That page can’t be found' => 'Lỗi 404! Trang web không tồn tại',
'It looks like nothing was found at this location. Maybe try one of the links below or a search'=> 'Chúng tôi không tìm thấy trang này trên hệ thống, vui lòng thử chức năng tìm kiếm bên dưới',
'Leave a comment' => 'Viết bình luận',
'Continue reading' => 'Đọc tiếp',
'View more' => 'Xem thêm',
'Category Archives' => 'Danh mục',
'Posted in' => 'Đăng tại',
'POSTED ON' => 'Đăng ngày',
'SHOPPING CART' => 'Giỏ hàng',
'CHECKOUT DETAILS' => 'Thông tin thanh toán',
'ORDER COMPLETE' => 'Hoàn tất đặt hàng',
'CATEGORY ARCHIVES' => 'Chuyên mục',
'MY ACCOUNT'=> 'Tài khoản của tôi',
);
$translated = str_ireplace( array_keys($text), $text, $translated );
return $translated;
}
add_filter( 'gettext', 'ra_change_translate_text_multiple', 20 );


48. Đổi tên nút Mua hàng khi sản phẩm có biến thể

add_filter( 'woocommerce_product_add_to_cart_text', function( $text ) {
global $product;
if ( $product->is_type( 'variable' ) ) {
$text = $product->is_purchasable() ? __( 'Mua hàng', 'woocommerce' ) : __( 'Read more', 'woocommerce' );
}
return $text;
}, 10 );

49. Xóa Notice: Function _load_textdomain_just_in_time được gọi không chính xác Wordpress 6.7

add_filter('doing_it_wrong_trigger_error', function($trigger_error, $function) {
    if ($function === '_load_textdomain_just_in_time') {
        return false;
    }
    return $trigger_error;
}, 10, 2);

50. Đổi text hoặc url "Quay về trang chủ" theo nhu cầu khi giỏ hàng trống.

add_filter('woocommerce_return_to_shop_redirect', function($default_url) {
    return home_url(); // Đường dẫn về trang chủ
});

add_filter('woocommerce_return_to_shop_text', function($default_text) {
    return 'Quay về trang chủ'; // Thay đổi text của nút
});

51. Chèn meta tag vào thẻ head của wordpress

/* Google Site Verification */
function google_site_verification() {
    ?>
  <meta name="google-site-verification" content="GxDGB74aDKV_kEQ1TftsyY_vcqM1eSM_vLx1y-L1qD0" />
    <?php
}
add_action('wp_head', 'google_site_verification');

hoặc

function third_party_tracking_code_header() { ?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XK9NGB6T6W"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XK9NGB6T6W');
</script>
<?php }
add_action( 'wp_head', 'third_party_tracking_code_header' );

52. Tối ưu wordpress

/* WordPress Cache */
define( 'WP_CACHE', true );

/* Compression */
define( 'COMPRESS_CSS', true );
define( 'COMPRESS_SCRIPTS', true );
define( 'CONCATENATE_SCRIPTS', true );
define( 'ENFORCE_GZIP', true );

/* Memory limit */
define('WP_MEMORY_LIMIT', '512M');

/* Debug */
define( 'WP_DEBUG', false );
define( 'WP_DEBUG_LOG', false );
define( 'WP_DEBUG_DISPLAY', false );

53. Tối ưu wordpress 2

// BẬT CLASSIC EDITOR
add_filter('use_block_editor_for_post', '__return_false');
add_filter('use_block_editor_for_post_type', '__return_false');

// Tắt hoàn toàn Block Editor (GUTENBERG)
add_filter('use_block_editor_for_post', '__return_false', 10);
add_filter('use_block_editor_for_post_type', '__return_false', 10);

// TẮT LIÊN QUAN GUTENBERG CSS (CHO NHẸ HƠN)
function remove_gutenberg_styles() {
    wp_dequeue_style('wp-block-library');
    wp_dequeue_style('wp-block-library-theme');
    wp_dequeue_style('wc-block-style'); // nếu dùng WooCommerce
}
add_action('wp_enqueue_scripts', 'remove_gutenberg_styles', 100);

// BẬT CLASSIC WIDGET
add_filter('use_widgets_block_editor', '__return_false');

// Tắt XML-RPC
add_filter('xmlrpc_enabled', '__return_false');

// Tắt REST API cho khách
add_filter('rest_authentication_errors', function($result) {
    if (!is_user_logged_in()) {
        return new WP_Error('rest_disabled', 'REST API bị tắt với người dùng chưa đăng nhập.', ['status' => 403]);
    }
    return $result;
});

// Ẩn phiên bản WordPress
remove_action('wp_head', 'wp_generator');

// Tắt Emoji
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
add_filter('emoji_svg_url', '__return_false');

// Tắt RSS Feed
function ttoiwp_disable_feeds() {
    wp_die(__('RSS feed bị tắt. Vui lòng truy cập trang chủ.'));
}
add_action('do_feed', 'ttoiwp_disable_feeds', 1);
add_action('do_feed_rdf', 'ttoiwp_disable_feeds', 1);
add_action('do_feed_rss', 'ttoiwp_disable_feeds', 1);
add_action('do_feed_rss2', 'ttoiwp_disable_feeds', 1);
add_action('do_feed_atom', 'ttoiwp_disable_feeds', 1);

// Giảm Heartbeat (giúp tiết kiệm CPU)
add_filter('heartbeat_send', function($response) {
    return $response;
});
add_filter('heartbeat_settings', function($settings) {
    $settings['interval'] = 60;
    return $settings;
});

// Tắt Dashicons ngoài admin
add_action('wp_enqueue_scripts', function() {
    if (!is_user_logged_in()) {
        wp_deregister_style('dashicons');
    }
});
// Bật auto update plugin
add_filter('auto_update_plugin', '__return_true');

// Bật auto update theme
add_filter('auto_update_theme', '__return_true');

// Bật auto update core WordPress (bao gồm major và minor)
add_filter('allow_minor_auto_core_updates', '__return_true'); // Minor updates
add_filter('allow_major_auto_core_updates', '__return_true'); // Major updates
add_filter('automatic_updater_disabled', '__return_false');   // Đảm bảo updater luôn bật

// THÊM CÔNG CỤ MỞ RỘNG CHO CLASSIC EDITOR
function webviet_extend_editor_toolbar($buttons) {
    // Dòng 1: thêm các công cụ mở rộng
    array_push($buttons,
        'fontselect',        // chọn font chữ
        'fontsizeselect',    // chọn cỡ chữ
        'backcolor',         // tô nền chữ
        'superscript',       // chỉ số trên
        'subscript',         // chỉ số dưới
        'hr',                // dòng kẻ ngang
        'anchor',            // tạo anchor
        'removeformat'       // xóa định dạng
    );
    return $buttons;
}
add_filter('mce_buttons_2', 'webviet_extend_editor_toolbar');

54



55



56



57



58



59



60




Mới hơn Cũ hơn