Uname:Linux ngoinhaweb 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64

Base Dir : /home/bepchaubkTW/bepchauau365.vn/public_html

User : bepchaubkTW


403WebShell
403Webshell
Server IP : 103.20.97.79  /  Your IP : 216.73.217.78
Web Server : nginx/1.20.1
System : Linux ngoinhaweb 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User : bepchaubkTW ( 1005)
PHP Version : 8.3.21
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/bepchaubkTW/bepchauau365.vn/public_html/wp-content/themes/flatsome-child/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/bepchaubkTW/bepchauau365.vn/public_html/wp-content/themes/flatsome-child/functions.php
<?php
// Add custom Theme Functions here
/*
* Add quick buy button go to checkout after click
* Author: levantoan.com
*/
add_action('woocommerce_after_add_to_cart_button','devvn_quickbuy_after_addtocart_button');
function devvn_quickbuy_after_addtocart_button(){
    global $product;
    ?>
    <style>
        .devvn-quickbuy button.single_add_to_cart_button.loading:after {
            display: none;
        }
        .devvn-quickbuy button.single_add_to_cart_button.button.alt.loading {
            color: #fff;
            pointer-events: none !important;
        }
        .devvn-quickbuy button.buy_now_button {
            position: relative;
            color: rgba(255,255,255,0.05);
        }
        .devvn-quickbuy button.buy_now_button:after {
            animation: spin 500ms infinite linear;
            border: 2px solid #fff;
            border-radius: 32px;
            border-right-color: transparent !important;
            border-top-color: transparent !important;
            content: "";
            display: block;
            height: 16px;
            top: 50%;
            margin-top: -8px;
            left: 50%;
            margin-left: -8px;
            position: absolute;
            width: 16px;
        }
    </style>
    <button type="button" class="button buy_now_button">
        <?php _e('Thêm vào giỏ hàng', 'devvn'); ?>
    </button>
    <input type="hidden" name="is_buy_now" class="is_buy_now" value="0" autocomplete="off"/>
    <script>
        jQuery(document).ready(function(){
            jQuery('body').on('click', '.buy_now_button', function(e){
                e.preventDefault();
                var thisParent = jQuery(this).parents('form.cart');
                if(jQuery('.single_add_to_cart_button', thisParent).hasClass('disabled')) {
                    jQuery('.single_add_to_cart_button', thisParent).trigger('click');
                    return false;
                }
                thisParent.addClass('devvn-quickbuy');
                jQuery('.is_buy_now', thisParent).val('1');
                jQuery('.single_add_to_cart_button', thisParent).trigger('click');
            });
        });
    </script>
    <?php
}
add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($redirect_url) {
    if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
        $redirect_url = wc_get_cart_url(); //or wc_get_cart_url()
    }
    return $redirect_url;
}

// Add custom Theme Functions here
if ( ! function_exists( 'devvn_ilc_mce_buttons' ) ) {
    function devvn_ilc_mce_buttons($buttons){
        array_push($buttons,
            "alignjustify",
            "subscript",
            "superscript"
        );
        return $buttons;
    }
    add_filter("mce_buttons", "devvn_ilc_mce_buttons");
}
if ( ! function_exists( 'devvn_ilc_mce_buttons_2' ) ) {
    function devvn_ilc_mce_buttons_2($buttons){
        array_push($buttons,
            "fontselect",
            "cleanup"
        );
        return $buttons;
    }
    add_filter("mce_buttons_2", "devvn_ilc_mce_buttons_2", 9999);
}
 
function flatsome_editor_text_sizes($initArray){
    $initArray['fontsize_formats'] = "9px 10px 12px 13px 14px 16px 17px 18px 19px 20px 21px 24px 28px 32px 36px";
    return $initArray;
};
//
/* Gutenberg
 *===============================================================*/
add_filter('use_block_editor_for_post', '__return_false', 10);
add_filter( 'use_block_editor_for_post_type', '__return_false', 9999 );
add_filter( 'use_block_editor_for_post', '__return_false', 9999 );
////
add_action('init', function () {
	if (is_admin()) {
		// stop queries to count comments, which are called when the admin menu is displayed
		add_filter('wp_count_comments', function() {
			return (object) [
				'approved'       => 0,
				'moderated'      => 0,
				'spam'           => 0,
				'trash'          => 0,
				'post-trashed'   => 0,
				'total_comments' => 0,
				'all'            => 0,
			];
		});
	}
});
add_filter('feed_links_show_comments_feed', '__return_false');
// Disable Comments
include('inc/disable-comments.php');
add_action('admin_init', function () {
	// Redirect any user trying to access comments page
	global $pagenow;

	if ($pagenow === 'edit-comments.php' || $pagenow === 'options-discussion.php') {
		wp_redirect(admin_url());
		exit;
	}

	// Remove comments metabox from dashboard
	remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

	// Disable support for comments and trackbacks in post types
	foreach (get_post_types() as $post_type) {
		if (post_type_supports($post_type, 'comments')) {
			remove_post_type_support($post_type, 'comments');
			remove_post_type_support($post_type, 'trackbacks');
		}
	}
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
  remove_menu_page('edit-comments.php');
	remove_submenu_page('options-general.php', 'options-discussion.php');
});

// Remove comments links from admin bar
add_action('init', function () {
	if (is_admin_bar_showing()) {
		remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
	}
});

// Remove comments icon from admin bar
add_action('wp_before_admin_bar_render', function() {
	global $wp_admin_bar;
	$wp_admin_bar->remove_menu('comments');
});
// Return a comment count of zero to hide existing comment entry link.
function zero_comment_count($count){
	return 0;
}
add_filter('get_comments_number', 'zero_comment_count');

// Multisite - Remove manage comments from admin bar
add_action( 'admin_bar_menu', 'remove_toolbar_items', PHP_INT_MAX -1 );
function remove_toolbar_items( $bar )
{
	$sites = get_blogs_of_user( get_current_user_id() );
	foreach ( $sites as $site )
	{
		$bar->remove_node( "blog-{$site->userblog_id}-c" );
	}
}
// Disable Flatsome Portfolio Custom Post Type
add_action( 'init', 'remove_flatsome_portfolio_cpt', 99 );
function remove_flatsome_portfolio_cpt() {
    unregister_post_type( 'featured_item' );
    unregister_taxonomy_for_object_type( 'featured_item_category', 'featured_item' );
    unregister_taxonomy_for_object_type( 'featured_item_tag', 'featured_item' );
}
//
add_action( 'wp_footer', function() {
?>
<style>
select.search_categories {
    width: 140px !important;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const select = document.querySelector('select.search_categories');
    
    if (select) {
        // Đổi text "All"
        const firstOption = select.querySelector('option[value=""]');
        
        if (firstOption && firstOption.textContent.trim() === 'All') {
            firstOption.textContent = 'Tất cả sản phẩm';
        }

        // Đặt chiều rộng
        select.style.width = '140px';
    }
});
</script>
<?php
});
//
add_action( 'wp_footer', function() {
?>
<style>
/* Chỉ áp dụng trên desktop */
@media (min-width: 850px) {
.header-nav.header-nav-main.nav.nav-left.nav-uppercase {
    width: 588px !important;
   min-width: 588px !important;
   max-width: 588px !important;
}
}
</style>
<?php
});
///
add_action( 'wp_footer', function() {
?>
<style>
/* Chỉ áp dụng trên desktop */
@media (min-width: 850px) {
    .header-nav.header-nav-main.nav.nav-right.nav-uppercase {
        width: 300px !important;
        min-width: 300px !important;
        max-width: 300px !important;
    }
}
</style>
<?php
});
// Add custom Theme Functions here
function ttit_add_element_ux_builder(){
  add_ux_builder_shortcode('title_with_cat', array(
    'name'      => __('Title With Category'),
    'category'  => __('Content'),
    'info'      => '{{ text }}',
    'wrap'      => false,
    'options' => array(
      'ttit_cat_ids' => array(
        'type' => 'select',
        'heading' => 'Categories',
        'param_name' => 'ids',
        'config' => array(
          'multiple' => true,
          'placeholder' => 'Select...',
          'termSelect' => array(
            'post_type' => 'product_cat',
            'taxonomies' => 'product_cat'
          )
        )
      ),
      'style' => array(
        'type'    => 'select',
        'heading' => 'Style',
        'default' => 'normal',
        'options' => array(
          'normal'      => 'Normal',
          'center'      => 'Center',
          'bold'        => 'Left Bold',
          'bold-center' => 'Center Bold',
        ),
      ),
      'text' => array(
        'type'       => 'textfield',
        'heading'    => 'Title',
        'default'    => 'Lorem ipsum dolor sit amet...',
        'auto_focus' => true,
      ),
      'tag_name' => array(
        'type'    => 'select',
        'heading' => 'Tag',
        'default' => 'h3',
        'options' => array(
          'h1' => 'H1',
          'h2' => 'H2',
          'h3' => 'H3',
          'h4' => 'H4',
        ),
      ),
      'color' => array(
        'type'     => 'colorpicker',
        'heading'  => __( 'Color' ),
        'alpha'    => true,
        'format'   => 'rgb',
        'position' => 'bottom right',
      ),
      'width' => array(
        'type'    => 'scrubfield',
        'heading' => __( 'Width' ),
        'default' => '',
        'min'     => 0,
        'max'     => 1200,
        'step'    => 5,
      ),
      'margin_top' => array(
        'type'        => 'scrubfield',
        'heading'     => __( 'Margin Top' ),
        'default'     => '',
        'placeholder' => __( '0px' ),
        'min'         => - 100,
        'max'         => 300,
        'step'        => 1,
      ),
      'margin_bottom' => array(
        'type'        => 'scrubfield',
        'heading'     => __( 'Margin Bottom' ),
        'default'     => '',
        'placeholder' => __( '0px' ),
        'min'         => - 100,
        'max'         => 300,
        'step'        => 1,
      ),
      'size' => array(
        'type'    => 'slider',
        'heading' => __( 'Size' ),
        'default' => 100,
        'unit'    => '%',
        'min'     => 20,
        'max'     => 300,
        'step'    => 1,
      ),
      'link_text' => array(
        'type'    => 'textfield',
        'heading' => 'Link Text',
        'default' => '',
      ),
      'link' => array(
        'type'    => 'textfield',
        'heading' => 'Link',
        'default' => '',
      ),
    ),
  ));
}
add_action('ux_builder_setup', 'ttit_add_element_ux_builder');
function title_with_cat_shortcode( $atts, $content = null ){
  extract( shortcode_atts( array(
    '_id' => 'title-'.rand(),
    'class' => '',
    'visibility' => '',
    'text' => 'Lorem ipsum dolor sit amet...',
    'tag_name' => 'h3',
    'sub_text' => '',
    'style' => 'normal',
    'size' => '100',
    'link' => '',
    'link_text' => '',
    'target' => '',
    'margin_top' => '',
    'margin_bottom' => '',
    'letter_case' => '',
    'color' => '',
    'width' => '',
    'icon' => '',
  ), $atts ) );
  $classes = array('container', 'section-title-container');
  if ( $class ) $classes[] = $class;
  if ( $visibility ) $classes[] = $visibility;
  $classes = implode(' ', $classes);
  $link_output = '';
  if($link) $link_output = '<a href="'.$link.'" target="'.$target.'">'.$link_text.get_flatsome_icon('icon-angle-right').'</a>';
  $small_text = '';
  if($sub_text) $small_text = '<small class="sub-title">'.$atts['sub_text'].'</small>';
  if($icon) $icon = get_flatsome_icon($icon);
  // fix old
  if($style == 'bold_center') $style = 'bold-center';
  $css_args = array(
   array( 'attribute' => 'margin-top', 'value' => $margin_top),
   array( 'attribute' => 'margin-bottom', 'value' => $margin_bottom),
  );
  if($width) {
    $css_args[] = array( 'attribute' => 'max-width', 'value' => $width);
  }
  $css_args_title = array();
  if($size !== '100'){
    $css_args_title[] = array( 'attribute' => 'font-size', 'value' => $size, 'unit' => '%');
  }
  if($color){
    $css_args_title[] = array( 'attribute' => 'color', 'value' => $color);
  }
  if ( isset( $atts[ 'ttit_cat_ids' ] ) ) {
    $ids = explode( ',', $atts[ 'ttit_cat_ids' ] );
    $ids = array_map( 'trim', $ids );
    $parent = '';
    $orderby = 'include';
  } else {
    $ids = array();
  }
  $args = array(
    'taxonomy' => 'product_cat',
    'include'    => $ids,
    'pad_counts' => true,
    'child_of'   => 0,
  );
  $product_categories = get_terms( $args );
  $hdevvn_html_show_cat = '';
  if ( $product_categories ) {
    foreach ( $product_categories as $category ) {
      $term_link = get_term_link( $category );
      $thumbnail_id = get_woocommerce_term_meta( $category->term_id, 'thumbnail_id', true  );
      if ( $thumbnail_id ) {
        $image = wp_get_attachment_image_src( $thumbnail_id, $thumbnail_size);
        $image = $image[0];
      } else {
        $image = wc_placeholder_img_src();
      }
      $hdevvn_html_show_cat .= '<li class="hdevvn_cats"><a href="'.$term_link.'">'.$category->name.'</a></li>';
    }
  }
  return '<div class="'.$classes.'" '.get_shortcode_inline_css($css_args).'><'. $tag_name . ' class="section-title section-title-'.$style.'"><b></b><span class="section-title-main" '.get_shortcode_inline_css($css_args_title).'>'.$icon.$text.$small_text.'<img title="Ấn tượng với cách tạo hình từ thuộc tính CSS border " alt="triangle_right" src="https://bepchauau365.vn/wp-content/uploads/2019/07/triangle_right-hc-50.png"></span>
  <span class="hdevvn-show-cats">'.$hdevvn_html_show_cat.'</span><b></b>'.$link_output.'</' . $tag_name .'></div><!-- .section-title -->';
}
add_shortcode('title_with_cat', 'title_with_cat_shortcode');
//
function redirect_attachment_to_parent() {
    if ( is_attachment() ) {
        global $post;
        if ( $post && $post->post_parent ) {
            wp_redirect( get_permalink( $post->post_parent ), 301 );
            exit;
        } else {
            wp_redirect( home_url(), 301 );
            exit;
        }
    }
}
add_action( 'template_redirect', 'redirect_attachment_to_parent' );
//
add_action('wp_head', 'custom_bg_he_thong_chi_nhanh');
function custom_bg_he_thong_chi_nhanh() {
    // Kiểm tra đúng đường dẫn (slug) của trang
    if ( is_page('he-thong-chi-nhanh') ) {
        echo '<style>
            body, .wrapper, #main-content {
                background-color: #E8ECF6 !important;
            }
        </style>';
    }
}
//
/* ============================================================================
   1. TẠO CHECKBOX CHỌN NHÃN DÁN TRONG TRANG QUẢN TRỊ SẢN PHẨM WOOCOMMERCE
============================================================================ */
add_action('woocommerce_product_options_general_product_data', 'hacom_add_custom_badge_fields');
function hacom_add_custom_badge_fields() {
    echo '<div class="options_group">';
    
    woocommerce_wp_checkbox(array(
        'id'            => '_badge_thanh_ly',
        'label'         => __('Hiện nhãn "THANH LÝ"', 'woocommerce'),
        'description'   => __('Gắn nhãn Thanh Lý ở góc trái ảnh sản phẩm.', 'woocommerce'),
        'desc_tip'      => true,
    ));
    
    woocommerce_wp_checkbox(array(
        'id'            => '_badge_big_sale',
        'label'         => __('Hiện nhãn "BIG SALE"', 'woocommerce'),
        'description'   => __('Gắn nhãn Big Sale ở góc trái ảnh sản phẩm.', 'woocommerce'),
        'desc_tip'      => true,
    ));
    
    woocommerce_wp_checkbox(array(
        'id'            => '_badge_sieu_re',
        'label'         => __('Hiện nhãn "SIÊU RẺ"', 'woocommerce'),
        'description'   => __('Gắn nhãn Siêu Rẻ ở góc phải bên dưới ảnh sản phẩm.', 'woocommerce'),
        'desc_tip'      => true,
    ));

    echo '</div>';
}

add_action('woocommerce_process_product_meta', 'hacom_save_custom_badge_fields');
function hacom_save_custom_badge_fields($post_id) {
    $badges = array('_badge_thanh_ly', '_badge_big_sale', '_badge_sieu_re');
    foreach ($badges as $badge) {
        $badge_value = isset($_POST[$badge]) ? 'yes' : 'no';
        update_post_meta($post_id, $badge, $badge_value);
    }
}

/* ============================================================================
   2. SHORTCODE HIỂN THỊ GIAO DIỆN (ĐÃ XÓA NÚT + VÀ KHO HÀNG)
============================================================================ */
function custom_recommended_products_shortcode($atts) {
    $atts = shortcode_atts(array(
        'limit'    => 10,
        'category' => 'san-pham-de-cu'
    ), $atts);

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => intval($atts['limit']),
        'tax_query'      => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $atts['category'],
            ),
        ),
        'orderby'        => 'date',
        'order'          => 'DESC',
    );

    $loop = new WP_Query($args);
    
    if (!$loop->have_posts()) {
        return '<p class="h-empty-msg">Hiện chưa có sản phẩm nào trong danh mục đề cử.</p>';
    }

    wp_enqueue_style('slick-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css');
    wp_enqueue_style('slick-theme-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css');
    wp_enqueue_script('slick-js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js', array('jquery'), null, true);

    $html = '<div class="h-clearance-section">';
    $html .= '    <div class="h-clearance-header">';
    $html .= '        <h2>SẢN PHẨM ĐỀ CỬ</h2>';
    $cat_link = get_term_link($atts['category'], 'product_cat');
    $view_all_url = !is_wp_error($cat_link) ? $cat_link : '#';
    $html .= '        <a href="' . esc_url($view_all_url) . '" class="view-all">Xem tất cả &rsaquo;</a>';
    $html .= '    </div>';
    
    $html .= '    <div class="h-clearance-grid h-slider-init">';

    while ($loop->have_posts()) : $loop->the_post();
        $product_id = get_the_ID();
        $product    = wc_get_product($product_id);
        if (!$product) continue;
        
        $title      = get_the_title();
        $permalink  = get_permalink();
        
        $image_id   = $product->get_image_id();
        $image_url  = wp_get_attachment_image_src($image_id, 'woocommerce_thumbnail');
        $image_src  = $image_url ? $image_url[0] : wc_placeholder_img_src();
        
        // 1. KIỂM TRA CHECKBOX NHÃN DÁN ĐỂ HIỂN THỊ
        $badge_html = '';
        if (get_post_meta($product_id, '_badge_thanh_ly', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-thanh-ly">THANH LÝ</div>';
        }
        if (get_post_meta($product_id, '_badge_big_sale', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-big-sale"><span>BIG SALE</span></div>';
        }
        if (get_post_meta($product_id, '_badge_sieu_re', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-sieu-re"><span>SIÊU RẺ</span></div>';
        }

        // 2. XỬ LÝ GIÁ BÁN HIỂN THỊ
        $price_html = '';
        if ($product->is_on_sale()) {
            $regular_price = (float) $product->get_regular_price();
            $sale_price    = (float) $product->get_sale_price();
            if ($regular_price > 0) {
                $discount_percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
                $price_html .= '<div class="h-old-price-wrap">';
                $price_html .= '    <span class="h-old-price">' . wc_price($regular_price) . '</span>';
                $price_html .= '    <span class="h-discount-tag">-' . $discount_percentage . '%</span>';
                $price_html .= '</div>';
            }
            $price_html .= '<div class="h-new-price">' . wc_price($sale_price) . '</div>';
        } else {
            $price_html .= '<div class="h-new-price">' . wc_price($product->get_price()) . '</div>';
        }
        
        // HTML CẤU TRÚC SẢN PHẨM (Đã bỏ Footer Trạng thái & Nút +)
        $html .= '<div class="h-clearance-card-wrap">'; 
        $html .= '  <div class="h-clearance-card">';
        $html .= '    <a href="' . esc_url($permalink) . '" class="h-card-link-mask"></a>';
        
        $html .= '    <div class="h-img-wrap">';
        $html .= '        ' . $badge_html;
        $html .= '        <img src="' . esc_url($image_src) . '" alt="' . esc_attr($title) . '">';
        $html .= '    </div>';
        
        $html .= '    <div class="h-price-group">' . $price_html . '</div>';
        $html .= '    <div class="h-product-title">' . esc_html($title) . '</div>';
        
        $html .= '  </div>';
        $html .= '</div>';
        
    endwhile;
    
    wp_reset_postdata();
    $html .= '    </div>';
    $html .= '</div>';
    
    // KỊCH BẢN JAVASCRIPT SLIDER (Giữ nguyên)
    $html .= '<script type="text/javascript">
        jQuery(document).ready(function($) {
            if($(".h-slider-init").length > 0) {
                $(".h-slider-init").slick({
                    slidesToShow: 5,
                    slidesToScroll: 1,
                    infinite: false,
                    arrows: true,
                    dots: false,
                    responsive: [
                        { breakpoint: 1025, settings: { slidesToShow: 3, slidesToScroll: 1 } },
                        { breakpoint: 768, settings: { slidesToShow: 2, slidesToScroll: 1, arrows: false } }
                    ]
                });
            }
        });
    </script>';
    
    return $html;
}
add_shortcode('sanpham_decu', 'custom_recommended_products_shortcode');
//
//
/* ============================================================================
   SHORTCODE: SẢN PHẨM BẠN ĐÃ VỪA XEM (Ẩn nếu xem dưới 5 sản phẩm)
============================================================================ */
function custom_recently_viewed_products_shortcode($atts) {
    // Cấu hình mặc định giới hạn 10 sản phẩm
    $atts = shortcode_atts(array(
        'limit' => 10,
    ), $atts);

    // Lấy danh sách ID sản phẩm vừa xem từ Cookie
    $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array();
    $viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );

    // [ĐIỀU KIỆN MỚI]: Nếu khách hàng xem CHƯA ĐỦ 5 sản phẩm -> Trả về rỗng (Ẩn hoàn toàn khối này)
    if ( count( $viewed_products ) < 5 ) {
        return ''; 
    }

    // Truy vấn lấy các sản phẩm
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => intval($atts['limit']),
        'post__in'       => $viewed_products,
        'orderby'        => 'post__in', 
    );

    $loop = new WP_Query($args);
    
    // Nếu lỗi query không ra sản phẩm -> Cũng ẩn hoàn toàn
    if (!$loop->have_posts()) {
        return '';
    }

    // Load lại thư viện Slick
    wp_enqueue_style('slick-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css');
    wp_enqueue_style('slick-theme-css', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css');
    wp_enqueue_script('slick-js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js', array('jquery'), null, true);

    // Bắt đầu xuất HTML
    $html = '<div class="h-clearance-section">';
    $html .= '    <div class="h-clearance-header">';
    $html .= '        <h2>Sản phẩm bạn đã vừa xem</h2>';
    $html .= '        <a href="' . esc_url(wc_get_page_permalink('shop')) . '" class="view-all">Xem tất cả &rsaquo;</a>';
    $html .= '    </div>';
    
    $html .= '    <div class="h-clearance-grid h-slider-init">';

    while ($loop->have_posts()) : $loop->the_post();
        $product_id = get_the_ID();
        $product    = wc_get_product($product_id);
        if (!$product) continue;
        
        $title      = get_the_title();
        $permalink  = get_permalink();
        
        $image_id   = $product->get_image_id();
        $image_url  = wp_get_attachment_image_src($image_id, 'woocommerce_thumbnail');
        $image_src  = $image_url ? $image_url[0] : wc_placeholder_img_src();
        
        // Nhãn dán
        $badge_html = '';
        if (get_post_meta($product_id, '_badge_thanh_ly', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-thanh-ly">THANH LÝ</div>';
        }
        if (get_post_meta($product_id, '_badge_big_sale', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-big-sale"><span>BIG SALE</span></div>';
        }
        if (get_post_meta($product_id, '_badge_sieu_re', true) === 'yes') {
            $badge_html .= '<div class="h-badge badge-sieu-re"><span>SIÊU RẺ</span></div>';
        }

        // Giá bán
        $price_html = '';
        if ($product->is_on_sale()) {
            $regular_price = (float) $product->get_regular_price();
            $sale_price    = (float) $product->get_sale_price();
            if ($regular_price > 0) {
                $discount_percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
                $price_html .= '<div class="h-old-price-wrap">';
                $price_html .= '    <span class="h-old-price">' . wc_price($regular_price) . '</span>';
                $price_html .= '    <span class="h-discount-tag">-' . $discount_percentage . '%</span>';
                $price_html .= '</div>';
            }
            $price_html .= '<div class="h-new-price">' . wc_price($sale_price) . '</div>';
        } else {
            $price_html .= '<div class="h-new-price">' . wc_price($product->get_price()) . '</div>';
        }
        
        // Khối Card HTML
        $html .= '<div class="h-clearance-card-wrap">'; 
        $html .= '  <div class="h-clearance-card">';
        $html .= '    <a href="' . esc_url($permalink) . '" class="h-card-link-mask"></a>';
        
        $html .= '    <div class="h-img-wrap">';
        $html .= '        ' . $badge_html;
        $html .= '        <img src="' . esc_url($image_src) . '" alt="' . esc_attr($title) . '">';
        $html .= '    </div>';
        
        $html .= '    <div class="h-price-group">' . $price_html . '</div>';
        $html .= '    <div class="h-product-title">' . esc_html($title) . '</div>';
        
        $html .= '  </div>';
        $html .= '</div>';
        
    endwhile;
    
    wp_reset_postdata();
    $html .= '    </div>';
    $html .= '</div>';
    
    // Khởi tạo JS cho Slider
    $html .= '<script type="text/javascript">
        jQuery(document).ready(function($) {
            if($(".h-slider-init").length > 0) {
                $(".h-slider-init").not(".slick-initialized").each(function() {
                    $(this).slick({
                        slidesToShow: 5,
                        slidesToScroll: 1,
                        infinite: false,
                        arrows: true,
                        dots: false,
                        responsive: [
                            { breakpoint: 1025, settings: { slidesToShow: 3, slidesToScroll: 1 } },
                            { breakpoint: 768, settings: { slidesToShow: 2, slidesToScroll: 1, arrows: false } }
                        ]
                    });
                });
            }
        });
    </script>';
    
    return $html;
}
// Nếu đoạn add_shortcode đã có từ trước, hệ thống sẽ tự đè lên hàm mới này (nhưng cứ đảm bảo dòng này vẫn còn ở cuối)
 add_shortcode('sanpham_vuaxem', 'custom_recently_viewed_products_shortcode');

/* ============================================================================
   BẮT BUỘC LƯU LỊCH SỬ XEM SẢN PHẨM VÀO COOKIE (FIX LỖI KHÔNG HIỂN THỊ)
============================================================================ */
add_action( 'template_redirect', 'hacom_force_track_product_view', 20 );
function hacom_force_track_product_view() {
    // Chỉ kích hoạt khi khách hàng đang ở trang Chi tiết sản phẩm
    if ( ! is_singular( 'product' ) ) {
        return;
    }

    global $post;
    
    // Lấy danh sách sản phẩm đã xem hiện tại
    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) {
        $viewed_products = array();
    } else {
        $viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) );
    }

    // Nếu sản phẩm đang xem đã có trong danh sách thì xóa đi để cập nhật nó lên đầu
    $keys = array_flip( $viewed_products );
    if ( isset( $keys[ $post->ID ] ) ) {
        unset( $viewed_products[ $keys[ $post->ID ] ] );
    }

    // Thêm sản phẩm vừa xem vào danh sách
    $viewed_products[] = $post->ID;

    // Chỉ lưu trữ tối đa 15 sản phẩm để không làm nặng trình duyệt
    if ( count( $viewed_products ) > 15 ) {
        array_shift( $viewed_products );
    }

    // Thiết lập lại Cookie, lưu trong 30 ngày (an toàn và tương thích)
    wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ), time() + 60 * 60 * 24 * 30 );
}
//
// 1. Xóa chữ category khỏi URL được tạo ra
add_filter('category_link', 'remove_category_base', 10, 2);
function remove_category_base($link, $category) {
    $category_base = get_option('category_base');
    if (empty($category_base)) {
        $category_base = 'category';
    }
    // Đảm bảo có dấu slash để replace chính xác
    $category_base .= '/';
    return str_replace($category_base, '', $link);
}

// 2. Thêm Rewrite Rules để WordPress hiểu URL mới (tránh lỗi 404)
add_filter('category_rewrite_rules', 'custom_category_rewrite_rules');
function custom_category_rewrite_rules() {
    global $wp_rewrite;
    $category_rewrite = array();
    $categories = get_categories(array('hide_empty' => false));
    
    foreach ($categories as $category) {
        $category_nicename = $category->slug;
        
        // Xử lý các danh mục con (Sub-categories)
        if ($category->parent == $category->cat_ID) {
            $category->parent = 0;
        } elseif ($category->parent != 0) {
            $category_nicename = get_category_parents($category->parent, false, '/', true) . $category_nicename;
        }
        
        // Tạo các rule cho pagination và feed
        $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
    }
    
    return $category_rewrite;
}
//
/*
 * Chức năng nhân đôi bài viết WordPress
 */
function rd_duplicate_post_as_draft(){
    global $wpdb;
    if (! ( isset( $_GET['post']) || isset( $_POST['post'])  || ( isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action'] ) )) {
        wp_die('Không có bài viết nào được chọn để nhân bản.');
    }

    $post_id = (isset($_GET['post']) ? absint($_GET['post']) : absint($_POST['post']));
    $post = get_post($post_id);

    $current_user = wp_get_current_user();
    $new_post_author = $current_user->ID;

    if (isset( $post ) && $post != null) {
        $args = array(
            'comment_status' => $post->comment_status,
            'ping_status'    => $post->ping_status,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_name'      => $post->post_name,
            'post_parent'    => $post->post_parent,
            'post_password'  => $post->post_password,
            'post_status'    => 'draft',
            'post_title'     => $post->post_title . ' (Bản sao)',
            'post_type'      => $post->post_type,
            'to_ping'        => $post->to_ping,
            'menu_order'     => $post->menu_order
        );

        $new_post_id = wp_insert_post( $args );

        $taxonomies = get_object_taxonomies($post->post_type);
        if ($taxonomies) {
            foreach ($taxonomies as $taxonomy) {
                $post_terms = wp_get_post_terms($post_id, $taxonomy, array('fields' => 'slugs'));
                wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
            }
        }

        $post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = $post_id");
        if ($post_meta_infos) {
            foreach ($post_meta_infos as $meta_info) {
                $meta_key = $meta_info->meta_key;
                $meta_value = addslashes($meta_info->meta_value);
                $wpdb->query("INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) VALUES ($new_post_id, '$meta_key', '$meta_value')");
            }
        }

        wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
        exit;
    } else {
        wp_die('Nhân bản thất bại. Không tìm thấy bài viết gốc.');
    }
}
add_action('admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft');

function rd_duplicate_post_link( $actions, $post ) {
    if (current_user_can('edit_posts')) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'nonce') . '" title="Nhân đôi bài viết này" rel="permalink">Nhân đôi</a>';
    }
    return $actions;
}
add_filter('post_row_actions', 'rd_duplicate_post_link', 10, 2);
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
//
/* ============================================================================
   SHORTCODE: TIN KHUYẾN MẠI & VIDEO REVIEW
============================================================================ */
function custom_news_promo_video_shortcode($atts) {
    $atts = shortcode_atts(array(
        'cat_promo' => 'tin-khuyen-mai',
        'cat_video' => 'video-review'
    ), $atts);

    // Lấy 5 bài cho Tin khuyến mại, và ĐÚNG 2 BÀI cho Video review như yêu cầu
    $promo_query = new WP_Query(array('post_type' => 'post', 'category_name' => $atts['cat_promo'], 'posts_per_page' => 5));
    $video_query = new WP_Query(array('post_type' => 'post', 'category_name' => $atts['cat_video'], 'posts_per_page' => 2));

    $html = '<div class="h-clearance-section">'; 
    $html .= '  <div class="h-news-container">'; 

    // ==========================================
    // KHỐI 1: TIN KHUYẾN MẠI (Trái)
    // ==========================================
    $html .= '      <div class="h-news-block">';
    
    $promo_cat = get_category_by_slug($atts['cat_promo']);
    $promo_link = $promo_cat ? get_category_link($promo_cat->term_id) : '#';
    $html .= '          <div class="h-news-header"><h3>TIN KHUYẾN MẠI</h3><a href="'.esc_url($promo_link).'">Xem thêm &rsaquo;</a></div>';
    
    $html .= '          <div class="h-promo-content">';
    if($promo_query->have_posts()) {
        $count = 0;
        while($promo_query->have_posts()) {
            $promo_query->the_post();
            $count++;
            $title = get_the_title();
            $link  = get_permalink();
            $img   = get_the_post_thumbnail_url(get_the_ID(), 'medium_large') ?: wc_placeholder_img_src();

            if($count == 1) {
                // Bài to đầu tiên: Gọi thêm đoạn mô tả ngắn (excerpt)
                // wp_strip_all_tags để loại bỏ các thẻ HTML rác giúp CSS xử lý dấu ... chuẩn nhất
                $excerpt = wp_strip_all_tags(get_the_excerpt());
                
                $html .= '          <div class="h-news-big-post">';
                $html .= '              <a href="'.$link.'"><img src="'.$img.'" alt="'.esc_attr($title).'"></a>';
                $html .= '              <h4><a href="'.$link.'">'.esc_html($title).'</a></h4>';
                $html .= '              <div class="h-news-excerpt">'.esc_html($excerpt).'</div>';
                $html .= '          </div>';
                
                $html .= '          <div class="h-news-small-list">'; 
            } else {
                // Các bài nhỏ tiếp theo
                $html .= '              <div class="small-post-item">';
                $html .= '                  <a href="'.$link.'"><img src="'.$img.'" alt="'.esc_attr($title).'"></a>';
                $html .= '                  <h4><a href="'.$link.'">'.esc_html($title).'</a></h4>';
                $html .= '              </div>';
            }
        }
        if($count > 0) $html .= '       </div>'; 
    } else {
        $html .= '          <p style="font-size:13px; color:#666;">Đang cập nhật tin khuyến mại...</p>';
    }
    wp_reset_postdata();
    $html .= '          </div>'; 
    $html .= '      </div>'; 

    // ==========================================
    // KHỐI 2: VIDEO REVIEW (Phải)
    // ==========================================
    $html .= '      <div class="h-news-block">';
    
    $video_cat = get_category_by_slug($atts['cat_video']);
    $video_link = $video_cat ? get_category_link($video_cat->term_id) : '#';
    $html .= '          <div class="h-news-header"><h3>VIDEO REVIEW</h3><a href="'.esc_url($video_link).'">Xem thêm &rsaquo;</a></div>';
    
    $html .= '          <div class="h-video-content">';
    if($video_query->have_posts()) {
        $count = 0;
        while($video_query->have_posts()) {
            $video_query->the_post();
            $count++;
            $title = get_the_title();
            $link  = get_permalink();
            $img   = get_the_post_thumbnail_url(get_the_ID(), 'medium_large') ?: wc_placeholder_img_src();

            if($count == 1) {
                // Video to đầu tiên (Tiêu đề tự động được CSS ép xuống 2 dòng)
                $html .= '          <div class="h-news-big-post">';
                $html .= '              <a href="'.$link.'"><img src="'.$img.'" alt="'.esc_attr($title).'"></a>';
                $html .= '              <h4><a href="'.$link.'">'.esc_html($title).'</a></h4>';
                $html .= '          </div>';
                
                $html .= '          <div class="h-news-small-list">';
            } else {
                // Video nhỏ tiếp theo
                $html .= '              <div class="small-post-item">';
                $html .= '                  <a href="'.$link.'"><img src="'.$img.'" alt="'.esc_attr($title).'"></a>';
                $html .= '                  <h4><a href="'.$link.'">'.esc_html($title).'</a></h4>';
                $html .= '              </div>';
            }
        }
        if($count > 0) $html .= '       </div>';
    } else {
        $html .= '          <p style="font-size:13px; color:#666;">Đang cập nhật video...</p>';
    }
    wp_reset_postdata();
    $html .= '          </div>'; 
    $html .= '      </div>'; 

    $html .= '  </div>'; 
    $html .= '</div>'; 
    
    return $html;
}
// Nếu đã add shortcode ở bước trước thì bỏ qua dòng dưới
 add_shortcode('tintuc_khuyenmai_video', 'custom_news_promo_video_shortcode');
//
/* ============================================================================
   SHORTCODE: MỌI NGƯỜI CÙNG TÌM KIẾM (Gợi ý từ khóa)
============================================================================ */
function custom_popular_searches_shortcode($atts) {
    // 1. Cấu hình tiêu đề và các từ khóa mặc định (ngăn cách bằng dấu phẩy)
    $atts = shortcode_atts(array(
        'title'    => 'Mọi người cùng tìm kiếm',
        'keywords' => 'Điều hòa, Tủ lạnh, Quạt mát, Tivi world cup, tivi 65 inch, Máy giặt, tivi 4k, Quạt cây, Quạt điều hòa, Tủ lạnh Toshiba, Tủ lạnh Hitachi, Máy giặt sấy, Máy giặt LG, Tủ lạnh LG, Tủ đông, Quạt trần, Quạt sạc, tủ lạnh mini, Máy Lọc Nước, Cây nước nóng lạnh, cây nước, Tủ sấy, Tủ mát, Lọc không khí, Máy sấy quần áo, Máy lọc không khí, Quạt treo tường'
    ), $atts);

    // 2. Chuyển chuỗi từ khóa thành mảng
    $keywords_array = explode(',', $atts['keywords']);

    // 3. Khởi tạo HTML (Bọc bằng .h-clearance-section để lấy viền nền xanh như yêu cầu)
    $html = '<div class="h-clearance-section">';
    $html .= '  <div class="h-search-tags-wrapper">';
    
    if (!empty($atts['title'])) {
        $html .= '      <h3>' . esc_html($atts['title']) . '</h3>';
    }
    
    $html .= '      <div class="h-search-tags-list">';
    
    // 4. Vòng lặp xuất từng từ khóa
    foreach ($keywords_array as $keyword) {
        $kw = trim($keyword);
        if (!empty($kw)) {
            // Tự động tạo link tìm kiếm sản phẩm cho WooCommerce
            $search_url = add_query_arg(array('s' => urlencode($kw), 'post_type' => 'product'), home_url('/'));
            $html .= '          <a href="' . esc_url($search_url) . '" class="h-search-tag-item">' . esc_html($kw) . '</a>';
        }
    }
    
    $html .= '      </div>';
    $html .= '  </div>';
    $html .= '</div>';

    return $html;
}
add_shortcode('timkiem_phobien', 'custom_popular_searches_shortcode');
//
//
/* ============================================================================
   SHORTCODE: DEAL THEO GIẢI PHÁP NHU CẦU (4 ẢNH + NÚT HTML)
============================================================================ */
function custom_deal_giai_phap_shortcode($atts) {
    // Cấu hình các thuộc tính. Nếu không nhập, sẽ dùng ảnh xám mặc định
    $atts = shortcode_atts(array(
        'title' => 'DEAL THEO GIẢI PHÁP NHU CẦU',
        'img1'  => 'https://via.placeholder.com/600x300/FFB800/fff?text=Anh+Deal+1',
        'link1' => '#',
        'img2'  => 'https://via.placeholder.com/600x300/28a745/fff?text=Anh+Deal+2',
        'link2' => '#',
        'img3'  => 'https://via.placeholder.com/600x300/007bff/fff?text=Anh+Deal+3',
        'link3' => '#',
        'img4'  => 'https://via.placeholder.com/600x300/6f42c1/fff?text=Anh+Deal+4',
        'link4' => '#',
    ), $atts);

    // Kế thừa lớp vỏ .h-clearance-section để giữ viền nền xanh tổng thể
    $html = '<div class="h-clearance-section">';
    $html .= '  <div class="h-deal-wrapper">';
    
    if (!empty($atts['title'])) {
        $html .= '      <h3>' . esc_html($atts['title']) . '</h3>';
    }
    
    $html .= '      <div class="h-deal-grid">';

    // Dùng vòng lặp tạo ra 4 thẻ ảnh
    for ($i = 1; $i <= 4; $i++) {
        $img_url = $atts['img'.$i];
        $link_url = $atts['link'.$i];
        
        if(!empty($img_url)) {
            $html .= '          <div class="h-deal-card">';
            // Lớp thẻ <a> ẩn bọc toàn hình để click được
            $html .= '              <a href="' . esc_url($link_url) . '" class="h-deal-mask"></a>';
            // Khung ảnh nền
            $html .= '              <img src="' . esc_url($img_url) . '" alt="Deal ' . $i . '">';
            // Nút bấm Xem ngay đè lên
            $html .= '              <a href="' . esc_url($link_url) . '" class="h-deal-btn">Xem ngay &rsaquo;</a>';
            $html .= '          </div>';
        }
    }

    $html .= '      </div>';
    $html .= '  </div>';
    $html .= '</div>';

    return $html;
}
add_shortcode('deal_giaiphap', 'custom_deal_giai_phap_shortcode');
//
/**
 * Ẩn danh mục 'Uncategorized' khỏi trang shop và vòng lặp sản phẩm trong WooCommerce
 */
// Hàm chèn JavaScript vào footer để ẩn danh mục Chưa phân loại (uncategorized)
add_action('wp_footer', 'custom_remove_uncategorized_option_js');
function custom_remove_uncategorized_option_js() {
    ?>
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            // Tìm thẻ option có giá trị 'uncategorized' trong thẻ select có name='product_cat'
            var uncatOption = document.querySelector('select[name="product_cat"] option[value="uncategorized"]');
            
            // Nếu tìm thấy, tiến hành xóa
            if (uncatOption) {
                uncatOption.remove(); 
            }
        });
    </script>
    <?php
}
//
//
add_action('wp_footer', 'custom_mobile_search_category_all_fixed');
function custom_mobile_search_category_all_fixed() {
    ?>
    <style>
        /* CSS CHỈ ÁP DỤNG CHO MOBILE (Màn hình dưới 768px) */
        @media (max-width: 768px) {
            .search-form-categories select.search_categories {
                width: 100px !important;
                max-width: 100px !important;
                /* Xử lý phần chữ tràn ra ngoài thành dấu ... */
                text-overflow: ellipsis !important;
                white-space: nowrap !important;
                overflow: hidden !important;
                /* Ẩn mũi tên trỏ xuống của thẻ select để tiết kiệm diện tích */
                -webkit-appearance: none !important;
                -moz-appearance: none !important;
                appearance: none !important;
                padding: 0 5px !important;
            }
        }
    </style>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            // Kiểm tra kích thước màn hình
            if (window.innerWidth <= 768) {
                // Thay vì querySelector, dùng querySelectorAll để quét TẤT CẢ các thanh tìm kiếm (Desktop, Mobile, Sticky...)
                var allOptions = document.querySelectorAll('.search-form-categories select[name="product_cat"] option[value=""]');
                
                // Lặp qua tất cả các thẻ tìm được và ép đổi tên
                allOptions.forEach(function(option) {
                    // Không cần kiểm tra xem chữ hiện tại có đúng là 'All' hay không nữa,
                    // chỉ cần value="" (nghĩa là danh mục gốc) thì tự động đổi.
                    option.textContent = 'Tất cả sản phẩm';
                });
            }
        });
    </script>
    <?php
}
// hide uncategory mobile searck
add_action('wp_footer', 'custom_mobile_search_categories_handler');
function custom_mobile_search_categories_handler() {
    ?>
    <style>
        /* CSS CHỈ ÁP DỤNG CHO MOBILE (Màn hình dưới 768px) */
        @media (max-width: 768px) {
            .search-form-categories select.search_categories {
                width: 100px !important;
                max-width: 100px !important;
                /* Xử lý phần chữ tràn ra ngoài thành dấu ... */
                text-overflow: ellipsis !important;
                white-space: nowrap !important;
                overflow: hidden !important;
                /* Ẩn mũi tên trỏ xuống của thẻ select */
                -webkit-appearance: none !important;
                -moz-appearance: none !important;
                appearance: none !important;
                padding: 0 5px !important;
            }
            
            /* Phương án dự phòng bằng CSS để ẩn danh mục Chưa phân loại */
            .search-form-categories select.search_categories option[value="uncategorized"] {
                display: none !important;
            }
        }
    </style>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            // Kiểm tra kích thước màn hình
            if (window.innerWidth <= 768) {
                
                // 1. TÌM VÀ ĐỔI TÊN DANH MỤC GỐC (VALUE="")
                var allOptions = document.querySelectorAll('.search-form-categories select[name="product_cat"] option[value=""]');
                allOptions.forEach(function(option) {
                    option.textContent = 'Tất cả sản phẩm';
                });

                // 2. TÌM VÀ XÓA DANH MỤC "CHƯA PHÂN LOẠI" (VALUE="uncategorized")
                var uncatOptions = document.querySelectorAll('.search-form-categories select[name="product_cat"] option[value="uncategorized"]');
                uncatOptions.forEach(function(option) {
                    option.remove(); 
                });
                
            }
        });
    </script>
    <?php
}
//
//
//
add_action('wp_footer', 'fix_vertical_menu_scroll_bug_homepage_only');
function fix_vertical_menu_scroll_bug_homepage_only() {
    // ĐIỀU KIỆN: Chỉ chạy code nếu là Trang chủ HOẶC Trang có ID 9130
    if ( ! is_front_page() && ! is_page(9130) ) {
        return; // Nếu không phải thì dừng lại, không chạy code bên dưới
    }
    ?>
    <style>
        /* CSS ép buộc hiển thị toàn bộ menu và phá vỡ giới hạn overflow */
        .tp-vertical-menu-container.force-show-menu {
            height: auto !important;
            opacity: 1 !important;
            visibility: visible !important;
            /* Giúp menu con cấp 1 hiển thị tràn ra bên ngoài */
            overflow: visible !important; 
        }
    </style>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            var menuContainer = document.querySelector('.tp-vertical-menu-container');

            if (menuContainer) {
                function handleMenuVisibility() {
                    // Kiểm tra nếu thanh cuộn đang ở trên cùng (vị trí <= 10px)
                    if (window.scrollY <= 10) {
                        // 1. Xóa style inline do script cũ của theme tự sinh ra
                        menuContainer.style.height = '';
                        
                        // 2. Thêm class ép hiển thị menu kèm menu con
                        menuContainer.classList.add('force-show-menu');
                    } else {
                        // Khi kéo xuống dưới, gỡ bỏ class để menu thu gọn lại
                        menuContainer.classList.remove('force-show-menu');
                    }
                }

                // Chạy ngay khi tải xong trang
                handleMenuVisibility();

                // Chạy mỗi khi cuộn chuột lên xuống
                window.addEventListener('scroll', handleMenuVisibility);
            }
        });
    </script>
    <?php
}
// popup call
// Gộp toàn bộ HTML, CSS và JS của Popup Hotline vào Footer
function add_custom_hotline_popup_to_footer() {
    ?>
    
    <style>
        /* Đổi con trỏ chuột khi rê vào vùng click */
        .supcallpop { cursor: pointer; }
        
        /* Giao diện Popup */
        .hl-popup-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 99999;
            justify-content: center;
            align-items: center;
            padding: 15px;
            box-sizing: border-box;
        }
        .hl-popup-content {
            background: #fff;
            width: 100%;
            max-width: 750px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            font-family: Arial, sans-serif;
        }
        .hl-popup-header {
            background: #0062cc;
            color: #fff;
			padding-left: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
			margin-bottom: -20px;
    margin-top: -20px;
        }
        .hl-popup-header h3 {
            margin: 0; font-weight: bold; text-transform: uppercase; font-size: 20px; color: #fff;
        }
        .hl-popup-close {
            background: none; border: none; color: #fff; font-size: 30px; cursor: pointer; line-height: 1; padding: 0; margin-bottom: 25px;
    margin-top: 25px;
        }
        .hl-popup-body { padding: 20px; background: #fff; }
        .hl-popup-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
        .hl-box { background: #e7f0ff; border-radius: 8px; padding: 15px; }
        .hl-full-width { width: 100%; box-sizing: border-box; }
        .hl-title {
            color: #0056b3; font-size: 16px; font-weight: bold; text-transform: uppercase;
            margin-top: 0; margin-bottom: 15px; border-bottom: 1px solid #e2ebf9; padding-bottom: 8px;
        }
        .hl-item { display: flex; align-items: center; margin-bottom: 12px; font-size: 14px; }
        .hl-item:last-child { margin-bottom: 0; }
        .hl-item-flex { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .hl-icon { width: 16px; height: 16px; color: #7b8eaf; margin-right: 8px; }
        .hl-phone { color: #d93025; font-weight: bold; font-size: 16px; text-decoration: none; margin-right: 8px; }
        .hl-phone:hover { text-decoration: underline; }
        .hl-name { color: #333; font-size: 16px; }
        
        @media (max-width: 600px) {
            .hl-popup-grid, .hl-item-flex { grid-template-columns: 1fr; }
            .hl-popup-header h3 { font-size: 20px; line-height: 1.4; }
        }
    </style>

    <div id="customHotlinePopup" class="hl-popup-overlay">
        <div class="hl-popup-content">
            <div class="hl-popup-header">
                <h3>LIÊN HỆ HOTLINE ĐỂ NHẬN ĐƯỢC TƯ VẤN TỐT NHẤT</h3>
                <button id="closeHotlinePopup" class="hl-popup-close">&times;</button>
            </div>
            <div class="hl-popup-body">
                <div class="hl-popup-grid">
                    <div class="hl-box">
                        <h4 class="hl-title">THIẾT BỊ NHÀ BẾP</h4>
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0932754264" class="hl-phone">0932.754.264</a> 
                            <span class="hl-name">Mr. Hoàng</span>
                        </div>
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0908293004" class="hl-phone">0908.293.004</a> 
                            <span class="hl-name">Ms. Hương</span>
                        </div>
                    </div>
                    <div class="hl-box">
                        <h4 class="hl-title">NỘI THẤT TỦ BẾP</h4>
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0985410396" class="hl-phone">0985.410.396</a> 
                            <span class="hl-name">Ms. Hường</span>
                        </div>
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0978007030" class="hl-phone">0978.007.030</a> 
                            <span class="hl-name">Ms. Song An</span>
                        </div>
                    </div>
                </div>
                <div class="hl-box hl-full-width">
                    <h4 class="hl-title">BẢO HÀNH - HỖ TRỢ KỸ THUẬT</h4>
                    <div class="hl-item-flex">
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0986100600" class="hl-phone">0986.100.600</a> 
                            <span class="hl-name">Mr. Tiệp Hoàng</span>
                        </div>
                        <div class="hl-item">
                            <svg class="hl-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                            <a href="tel:0934062146" class="hl-phone">0934.062.146</a> 
                            <span class="hl-name">Ms. An</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            var popup = document.getElementById("customHotlinePopup");
            var closeBtn = document.getElementById("closeHotlinePopup");
            
            // Lấy tất cả các class supcallpop trên website
            var triggerElements = document.querySelectorAll(".supcallpop");

            if(popup) {
                // Bật popup khi click vào phần tử
                triggerElements.forEach(function(triggerEl) {
                    triggerEl.addEventListener("click", function(e) {
                        e.preventDefault(); // Ngăn hành vi mặc định (tránh nhảy trang nếu thẻ click là <a>)
                        popup.style.display = "flex";
                    });
                });

                // Đóng popup qua nút X
                if(closeBtn) {
                    closeBtn.addEventListener("click", function() {
                        popup.style.display = "none";
                    });
                }

                // Đóng popup khi click ra ngoài nền mờ
                window.addEventListener("click", function(event) {
                    if (event.target == popup) {
                        popup.style.display = "none";
                    }
                });
            }
        });
    </script>
    
    <?php
}
// Gọi function này ra ở wp_footer
add_action('wp_footer', 'add_custom_hotline_popup_to_footer');
//
//
/* ============================================================================
   1. TẠO TRANG CÀI ĐẶT BANNER THÁNG VÀNG TRONG WP-ADMIN (CÀI ĐẶT)
============================================================================ */
add_action('admin_menu', 'hacom_banner_settings_menu');
function hacom_banner_settings_menu() {
    // Thêm menu con vào phần Cài đặt (options-general.php)
    add_options_page(
        'Cài đặt Banner Tháng Vàng', 
        'Banner Tháng Vàng', 
        'manage_options', 
        'hacom-banner-settings', 
        'hacom_banner_settings_page'
    );
}

add_action('admin_init', 'hacom_register_banner_settings');
function hacom_register_banner_settings() {
    // Đăng ký các trường dữ liệu lưu trữ
    register_setting('hacom_banner_options_group', 'hacom_brand_name');
    register_setting('hacom_banner_options_group', 'hacom_banner_image');
    register_setting('hacom_banner_options_group', 'hacom_banner_link');
}

// Giao diện trang cài đặt trong Admin
function hacom_banner_settings_page() {
    ?>
    <div class="wrap">
        <h2>Cài đặt Banner "Tháng vàng thương hiệu"</h2>
        <form method="post" action="options.php">
            <?php settings_fields('hacom_banner_options_group'); ?>
            <?php do_settings_sections('hacom_banner_options_group'); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">Tên thương hiệu:</th>
                    <td>
                        <input type="text" name="hacom_brand_name" value="<?php echo esc_attr(get_option('hacom_brand_name', 'COEX')); ?>" style="width: 400px;" />
                        <p class="description">Ví dụ: COEX, SAMSUNG, SONY... Tiêu đề sẽ tự động hiển thị là "Tháng vàng thương hiệu [Tên bạn nhập]"</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Link ảnh Banner:</th>
                    <td>
                        <input type="text" name="hacom_banner_image" value="<?php echo esc_attr(get_option('hacom_banner_image', '')); ?>" style="width: 400px;" />
                        <p class="description">Copy đường dẫn URL của hình ảnh từ Thư viện Media và dán vào đây.</p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row">Link liên kết (Đích đến):</th>
                    <td>
                        <input type="text" name="hacom_banner_link" value="<?php echo esc_attr(get_option('hacom_banner_link', '#')); ?>" style="width: 400px;" />
                        <p class="description">Link trang đích khi khách hàng click vào Banner (sẽ tự động mở tab mới).</p>
                    </td>
                </tr>
            </table>
            <?php submit_button('Lưu thay đổi'); ?>
        </form>
    </div>
    <?php
}

/* ============================================================================
   2. SHORTCODE HIỂN THỊ BANNER THÁNG VÀNG NGOÀI TRANG CHỦ
============================================================================ */
function custom_golden_month_banner_shortcode() {
    // Lấy dữ liệu từ cấu hình Admin
    $brand_name = get_option('hacom_brand_name', 'COEX');
    $image_url  = get_option('hacom_banner_image', '');
    $link_url   = get_option('hacom_banner_link', '#');

    // Nếu chưa nhập ảnh thì báo lỗi nhẹ để người dùng biết
    if (empty($image_url)) {
        return '<div class="h-clearance-section"><p class="h-empty-msg">Vui lòng vào Cài đặt > Banner Tháng Vàng để nhập link ảnh banner.</p></div>';
    }

    // Xuất HTML
    $html = '<div class="h-clearance-section">';
    $html .= '  <div class="h-banner-wrapper">';
    $html .= '      <h3>Tháng vàng thương hiệu <span class="h-brand-highlight">' . esc_html($brand_name) . '</span></h3>';
    
    // Thẻ a bọc ngoài ảnh, target="_blank" để mở trang mới
    $html .= '      <a href="' . esc_url($link_url) . '" target="_blank" rel="noopener noreferrer" class="h-banner-img-box">';
    $html .= '          <img src="' . esc_url($image_url) . '" alt="Tháng vàng thương hiệu ' . esc_attr($brand_name) . '">';
    $html .= '      </a>';
    
    $html .= '  </div>';
    $html .= '</div>';

    return $html;
}
add_shortcode('thangvang_thuonghieu', 'custom_golden_month_banner_shortcode');

Youez - 2016 - github.com/yon3zu
LinuXploit