<?php

/* TITLE - Kích hoạt title nếu chưa có */
add_theme_support( 'title-tag' );

/* IMG - Kích hoạt thumbnail nếu chưa có */
add_theme_support( 'post-thumbnails' );

/* IMG - Xóa size không cần thiết */
function pvaImg_removeDefaultSizes( $sizes) {
    unset( $sizes['medium_large']);
    return $sizes;
}
add_filter('intermediate_image_sizes_advanced','pvaImg_removeDefaultSizes');
update_option('medium_large_size_w', 0); update_option('medium_large_size_h', 0);
remove_image_size('1536x1536'); remove_image_size('2048x2048');

/* IMG - Đổi link CDN dùng srcset */
function pvaImg_cdnSrcset($html) {
    return preg_replace_callback(
        '/<img\s+[^>]*?src=["\']https:\/\/phanvananh\.com\/wp-content\/uploads\/(\d{4})\/(\d{2})\/([^"\']+)\.(jpg|png)["\'](?![^>]*\bsrcset=)[^>]*>/i',
        function($matches) {
            $year = $matches[1];      // yyyy
            $month = $matches[2];     // mm
            $filename = $matches[3];  // name without extension
            $ext = $matches[4];       // jpg or png
            // New domain and path for srcset
            $baseUrl = "https://webp.phanvananh.com/$year/$month";
            $srcset = "$baseUrl/{$filename}__resize--w480.$ext 480w, $baseUrl/{$filename}__resize--w768.$ext 768w, $baseUrl/{$filename}__resize--w1024.$ext 1024w";
            $sizes = "(min-width: 1024px) 1024px, (min-width: 768px) 768px, 480px";
            // Inject into the original img tag
            return preg_replace(
                '/>$/',
                " srcset=\"$srcset\" sizes=\"$sizes\" loading=\"lazy\">",
                $matches[0]
            );
        },
        $html
    );
}

/* CLEAN - Header */
remove_action ('wp_head', 'rsd_link');
remove_action( 'wp_head', 'wlwmanifest_link');
remove_action( 'wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('template_redirect', 'rest_output_link_header', 11, 0);
remove_action('wp_head', 'wp_oembed_add_discovery_links', 10);
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
add_filter( 'embed_oembed_discover', '__return_false' );
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
remove_action( 'wp_head', 'wp_oembed_add_host_js' );

/* CLEAN - Crunchify */
function pvaClean_crunchifyVersion() { return ''; }
add_filter('the_generator', 'pvaClean_crunchifyVersion');

/* CLEAN - Tắt RSS */
function pvaClean_rss() {
    wp_die( __( 'No feed, please visit the <a href="'. esc_url( home_url( '/' ) ) .'">homepage</a>!' ) );
}
add_action('do_feed', 'pvaClean_rss', 1);
add_action('do_feed_rdf', 'pvaClean_rss', 1);
add_action('do_feed_rss', 'pvaClean_rss', 1);
add_action('do_feed_rss2', 'pvaClean_rss', 1);
add_action('do_feed_atom', 'pvaClean_rss', 1);
add_action('do_feed_rss2_comments', 'pvaClean_rss', 1);
add_action('do_feed_atom_comments', 'pvaClean_rss', 1);
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);

/* CLEAN - Emoji */
function pvaClean_emojisTinymce($plugins) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpemoji' ) );
    } else return array();
}
function pvaClean_emojisDnsprefetch( $urls, $relation_type ) {
    if ( 'dns-prefetch' == $relation_type ) {
        /** This filter is documented in wp-includes/formatting.php */
        $emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );
        $urls = array_diff( $urls, array( $emoji_svg_url ) );
    }
    return $urls;
}
function pvaClean_emojis() {
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    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( 'tiny_mce_plugins', 'pvaClean_emojisTinymce' );
    add_filter( 'wp_resource_hints', 'pvaClean_emojisDnsprefetch', 10, 2 );
}
add_action( 'init', 'pvaClean_emojis' );


/* CLEAN - Embed */
function pvaClean_embed() {    if (!is_admin()) { wp_deregister_script('wp-embed'); } }
add_action('wp_enqueue_scripts', 'pvaClean_embed');

/* CLEAN - DNS prefetch */
function pvaClean_dnsPrefetch () { remove_action( 'wp_head', 'wp_resource_hints', 2, 99 ); }
add_action('init', 'pvaClean_dnsPrefetch');

/* CLEAN - GUTENBERG BLOCK LIBRARY CSS FROM LOADING ON FRONTEND */
function pvaClean_gutenbergCss(){
    wp_dequeue_style( 'wp-block-library' );
    wp_dequeue_style( 'wp-block-library-theme' );
    wp_dequeue_style( 'wc-block-style' ); // REMOVE WOOCOMMERCE BLOCK CSS
    wp_dequeue_style( 'global-styles' ); // REMOVE THEME.JSON
    wp_dequeue_style( 'global-styles-inline' );
    wp_dequeue_style( 'classic-theme-styles' );
}
add_action( 'wp_enqueue_scripts', 'pvaClean_gutenbergCss', 100 );

/* CLEAN - Rankmath */
function pvaClean_rankmathToc(){ wp_dequeue_style( 'rank-math-toc-block-style' ); }
add_action( 'wp_enqueue_scripts', 'pvaClean_rankmathToc', 100 );


/* TOC */
function pvaToc_show($content) {
    // Match <h2>, <h3>, <h4>, <h5> tags, capturing any class or other attributes
    preg_match_all('#<h[2-5][^>]*>.*?<\/h[2-5]>#', $content, $tocs);
    if ( empty($tocs) || empty($tocs[0]) ) { return ''; }
    $r = '<ol class="ps-1 m-0" style="list-style:none;">';
    $ch = 1; // Track the current header level
    foreach ($tocs[0] as $toc) {
        // Extract the title without the <h> tags
        $title = strip_tags(preg_replace('#<h[2-5][^>]*>|<\/h[2-5]>#', '', $toc));
        $string = sanitize_title($title); // Generate a sanitized ID
        if( is_numeric(substr($string,0,1)) ){ $string = 'p'.$string; }
        // Check if it's <h2>, <h3>, <h4>, or <h5> and handle accordingly
        if (strpos($toc, '<h2') !== false) {
            if ($ch >= 3) { $r .= '</ol>'; }
            if ($ch > 2) { $r .= '</li>'; }
            $r .= '<li><a class="text-dark" href="#' . $string . '">' . $title . '</a>';
            $new_toc = preg_replace('/(<h2\b[^>]*)(>)/', '$1 id="' . $string . '"$2', $toc); // Add ID while preserving class
            $content = str_replace($toc, $new_toc, $content);
            $ch = 2;
        } elseif (strpos($toc, '<h3') !== false) {
            if ($ch == 2) { $r .= '<ol style="list-style:none;">'; }
            $r .= '<li><a class="text-dark" href="#' . $string . '">' . $title . '</a>';
            $new_toc = preg_replace('/(<h3\b[^>]*)(>)/', '$1 id="' . $string . '"$2', $toc); // Add ID while preserving class
            $content = str_replace($toc, $new_toc, $content);
            $ch = 3;
        } elseif (strpos($toc, '<h4') !== false) {
            if ($ch == 3) { $r .= '<ol style="list-style:none;">'; }
            $r .= '<li><a class="text-dark" href="#' . $string . '">' . $title . '</a>';
            $new_toc = preg_replace('/(<h4\b[^>]*)(>)/', '$1 id="' . $string . '"$2', $toc); // Add ID while preserving class
            $content = str_replace($toc, $new_toc, $content);
            $ch = 4;
        } elseif (strpos($toc, '<h5') !== false) {
            if ($ch == 4) { $r .= '<ol style="list-style:none;">'; }
            $r .= '<li><a class="text-dark" href="#' . $string . '">' . $title . '</a>';
            $new_toc = preg_replace('/(<h5\b[^>]*)(>)/', '$1 id="' . $string . '"$2', $toc); // Add ID while preserving class
            $content = str_replace($toc, $new_toc, $content);
            $ch = 5;
        }
    }
    if ($ch >= 3) { $r .= '</ol>'; }
    $r .= '</ol>';
    // Split the content into two parts: before and after the first <h2>
    $e = explode('<h2 ', $content, 2);
    return array('toc' => $r, 'content' => $content, 'before' => $e[0], 'after' => '<h2 ' . $e[1]);
}


/* Breadcrumbs */
function pvaBreadcrumbs_show(){
    // Check if is front/home page, return
    if (is_front_page()) { return; }
    // Define
    global $post;
    $custom_taxonomy = ''; // If you have custom taxonomy place it here
    $defaults = array(
        'seperator' => apply_filters('breadcrumbs_seperator', '&#187;'),
        'id' => 'pva-breadcrumb',
        'classes' => 'breadcrumb',
        'home_title' => esc_html__('Trang chủ', '')
    );
    $sep = '<li class="seperator">' . esc_html($defaults['seperator']) . '</li>';
    $position = 1;
    // Start the breadcrumb with a link to your homepage
    echo '<ol itemscope itemtype="https://schema.org/BreadcrumbList" id="' . esc_attr($defaults['id']) . '" class="' . esc_attr($defaults['classes']) . '">';
    // Creating home link
    echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item"><a itemprop="item" href="' . get_home_url() . '"><span itemprop="name">' . esc_html($defaults['home_title']) . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
    $position++;
    if (is_single()) {
        // Get posts type
        $post_type = get_post_type();

        // If post type is not post
        if ($post_type != 'post') {
            $post_type_object = get_post_type_object($post_type);
            $post_type_link = get_post_type_archive_link($post_type);

            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-cat"><a itemprop="item" href="' . $post_type_link . '"><span itemprop="name">' . $post_type_object->labels->name . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
            $position++;
        }
        // Get categories
        $category = get_the_category($post->ID);
        // If category not empty
        if (!empty($category)) {
            // Arrange category parent to child
            $category_values = array_values($category);
            $get_last_category = end($category_values);
            // $get_last_category    = $category[count($category) - 1];
            $get_parent_category = rtrim(get_category_parents($get_last_category->term_id, true, ','), ',');
            $cat_parent = explode(',', $get_parent_category);

            // Store category in $display_category
            $display_category = '';
            foreach ($cat_parent as $p) {
                preg_match('#<a href="(.*)">(.*)</a>#', $p, $matches);
                $display_category .= '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-cat"><a itemscope itemtype="https://schema.org/WebPage" itemprop="item" itemid="'.$matches[1].'" href="'.$matches[1].'"><span itemprop="name">' . $matches[2] . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
                $position++;
            }
        }
        // If it's a custom post type within a custom taxonomy
        $taxonomy_exists = taxonomy_exists($custom_taxonomy);

        if (empty($get_last_category) && !empty($custom_taxonomy) && $taxonomy_exists) {
            $taxonomy_terms = get_the_terms($post->ID, $custom_taxonomy);
            $cat_id = $taxonomy_terms[0]->term_id;
            $cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy);
            $cat_name = $taxonomy_terms[0]->name;
        }
        // Check if the post is in a category
        if (!empty($get_last_category)) {
            echo $display_category;
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-current"><span itemprop="name">' . get_the_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (!empty($cat_id)) {
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-cat"><a itemprop="item" href="' . $cat_link . '"><span itemprop="name">' . $cat_name . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
            $position++;
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . get_the_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else {
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . get_the_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        }
    } else if (is_archive()) {
        if (is_tax()) {
            // Get posts type
            $post_type = get_post_type();
            // If post type is not post
            if ($post_type != 'post') {
                $post_type_object = get_post_type_object($post_type);
                $post_type_link = get_post_type_archive_link($post_type);
                echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-cat item-custom-post-type-' . $post_type . '"><a itemprop="item" href="' . $post_type_link . '"><span itemprop="name">' . $post_type_object->labels->name . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
                $position++;
            }
            $custom_tax_name = get_queried_object()->name;
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-current"><span itemprop="name">' . $custom_tax_name . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_category()) {
            $parent = get_queried_object()->category_parent;
            if ($parent !== 0) {
                $parent_category = get_category($parent);
                $category_link = get_category_link($parent);

                echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item"><a itemprop="item" href="' . esc_url($category_link) . '"><span itemprop="name">' . $parent_category->name . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
                $position++;
            }
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-current"><span itemprop="name">' . single_cat_title('', false) . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_tag()) {
            // Get tag information
            $term_id = get_query_var('tag_id');
            $taxonomy = 'post_tag';
            $args = 'include=' . $term_id;
            $terms = get_terms($taxonomy, $args);
            $get_term_name = $terms[0]->name;
            // Display the tag name
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . $get_term_name . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_day()) {
            // Day archive
            // Year link
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-year item"><a itemprop="item" href="' . get_year_link(get_the_time('Y')) . '"><span itemprop="name">' . get_the_time('Y') . ' Archives</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
            $position++;
            // Month link
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-month item"><a itemprop="item" href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '"><span itemprop="name">' . get_the_time('M') . ' Archives</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
            $position++;

            // Day display
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . get_the_time('jS') . ' ' . get_the_time('M') . ' Archives</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_month()) {
            // Month archive
            // Year link
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-year item"><a itemprop="item" href="' . get_year_link(get_the_time('Y')) . '"><span itemprop="name">' . get_the_time('Y') . ' Archives</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
            $position++;

            // Month Display
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-month item-current item"><span itemprop="name">' . get_the_time('M') . ' Archives</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_year()) {
            // Year Display
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-year item-current item"><span itemprop="name">' . get_the_time('Y') . ' Archives</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else if (is_author()) {
            // Auhor archive
            // Get the author information
            global $author;
            $userdata = get_userdata($author);

            // Display author name
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . 'Author: ' . $userdata->display_name . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else {
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item item-current"><span itemprop="name">' . post_type_archive_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        }
    } else if (is_page()) {
        // Standard page
        if ($post->post_parent) {
            // If child page, get parents
            $anc = get_post_ancestors($post->ID);

            // Get parents in the right order
            $anc = array_reverse($anc);

            // Parent page loop
            if (!isset($parents)) $parents = null;
            foreach ($anc as $ancestor) {
                $parents .= '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-parent item"><a itemprop="item" href="' . get_permalink($ancestor) . '"><span itemprop="name">' . get_the_title($ancestor) . '</span></a><meta itemprop="position" content="'.$position.'" /></li>' . $sep;
                $position++;
            }
            // Display parent pages
            echo $parents;
            // Current page
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . get_the_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        } else {
            // Just display current page if not parents
            echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . get_the_title() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
            $position++;
        }
    } else if (is_search()) {
        // Search results page
        echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">Search results for: ' . get_search_query() . '</span><meta itemprop="position" content="'.$position.'" /></li>';
        $position++;
    } else if (is_404()) {
        // 404 page
        echo '<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="item-current item"><span itemprop="name">' . 'Error 404' . '</span><meta itemprop="position" content="'.$position.'" /></li>';
        $position++;
    }
    echo '</ol>'; // End breadcrumb
}


/* NAV - Menu Simple */
function pvaNav_simple($menu_location) {
    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_location ] ) ) {
        $menu = get_term( $locations[ $menu_location ] );
        $array_menu = wp_get_nav_menu_items($menu->term_id);
        $menu = array();
        foreach ($array_menu as $m) {
            if (empty($m->menu_item_parent)) {
                $menu[$m->ID] = array();
                $menu[$m->ID]['ID'] = $m->ID;
                $menu[$m->ID]['title'] = $m->title;
                $menu[$m->ID]['url'] = $m->url;
                $menu[$m->ID]['children'] = array();
            }
        }
        $submenu = array();
        foreach ($array_menu as $m) {
            if ($m->menu_item_parent) {
                $submenu[$m->ID] = array();
                $submenu[$m->ID]['ID'] = $m->ID;
                $submenu[$m->ID]['title'] = $m->title;
                $submenu[$m->ID]['url'] = $m->url;
                $menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
            }
        }
        return $menu;
    }
}

/* NAV - Admin Sharing Debug */
function pvaNav_adminShareDebug($wp_admin_bar){
    $wp_admin_bar->add_node(array('id'=>'admin-facebookdebug','title'=>'Facebook Debug','href'=>'https://developers.facebook.com/tools/debug/?locale=vi_VN','meta'=> array('class'=>'admin-facebookdebug','target'=>'_blank')));
    $wp_admin_bar->add_node(array('id'=>'admin-zalodebug','title'=>'Zalo Debug','href'=>'https://developers.zalo.me/tools/debug-sharing','meta'=> array('class'=>'admin-zalodebug','target'=>'_blank')));
}
add_action('admin_bar_menu', 'pvaNav_adminShareDebug', 90);


/* Bài viết liên quan theo post_id */
function pvaPost_relates($post_id, $related_count = 4) {
    $related_posts = array(); $tag_ids = array();
    if( get_post_type($post_id) == 'page' ){
        $top_categories = get_terms(array(
            'taxonomy'   => 'category', // Chỉ lấy danh mục của bài viết
            'orderby'    => 'count',    // Sắp xếp theo số bài viết
            'order'      => 'DESC',     // Lấy danh mục có nhiều bài viết nhất trước
            'number'     => 1,          // Chỉ lấy 1 danh mục
        ));
        $categories = array($top_categories[0]->term_id);
    }else{
        // Get current post categories and tags
        $categories = wp_get_post_categories($post_id); $tags = wp_get_post_tags($post_id);
        // Prepare category and tag IDs for query
        $category_ids = array();
        // foreach ($categories as $category) { $category_ids[] = $category->term_id; }
        // foreach ($tags as $tag) { $tag_ids[] = $tag->term_id; }
    }
    // Query arguments to find related posts
    $args = array(
        'post__not_in' => array($post_id), // Exclude the current post
        'posts_per_page' => $related_count, // Number of related posts to display
        'orderby' => 'rand', // Order by random to show different related posts each time
        'tax_query' => array(
            'relation' => 'OR',
            array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => $categories, 'operator' => 'IN' ),
            array( 'taxonomy' => 'post_tag', 'field' => 'id', 'terms' => $tag_ids, 'operator' => 'IN' ),
        ),
    );
    // Perform the query
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $related_posts[] = array(
                'title' => get_the_title(),
                'permalink' => get_permalink(),
                'thumbnail' => get_the_post_thumbnail_url()
            );
        }
    }
    wp_reset_postdata();
    return $related_posts;
}


/* WPML - Kiểm tra có sử dụng WPML không */
function pvaWpml_isActive() { return defined('ICL_SITEPRESS_VERSION'); }

/* WPML - Redirect 404 về đúng ngôn ngữ */
function pvaWpml_redirect404() {
    if (is_404()) {
        $current_lang = apply_filters('wpml_current_language', null);
        $home_url = get_home_url(null, '/', $current_lang);
        wp_redirect($home_url, 301);
        exit;
    }
}
add_action('template_redirect', 'pvaWpml_redirect404', 1);


/* POST - Lấy Post ID từ sLug */
function pvaPost_idBySlug($slug) {
    // Check if it's a custom taxonomy term
    $custom_taxonomies = get_taxonomies(array('public' => true), 'names'); // Get all public taxonomies
    foreach ($custom_taxonomies as $taxonomy) {
        $term = get_term_by('slug', $slug, $taxonomy);
        if ($term) {
            // If it's a custom taxonomy term, return the term ID
            return array('type' => 'custom_taxonomy', 'taxonomy' => $taxonomy, 'term_id' => $term->term_id);
        }
    }
    // Check if it's a custom post type
    $custom_post_types = get_post_types(array('public' => true), 'names'); // Get all public post types
    foreach ($custom_post_types as $post_type) {
        $post = get_page_by_path($slug, OBJECT, $post_type);
        if ($post) {
            // If it's a custom post type, return the post ID
            return array('type' => 'custom_post_type', 'post_type' => $post_type, 'post_id' => $post->ID);
        }
    }
    // Check for default taxonomies (category and tag)
    // Check if it's a category
    $category = get_term_by('slug', $slug, 'category');
    if ($category) { return array('type' => 'category', 'term_id' => $category->term_id); }
    // Check if it's a tag
    $tag = get_term_by('slug', $slug, 'post_tag');
    if ($tag) { return array('type' => 'tag', 'term_id' => $tag->term_id); }
    // Check if it's a post
    $post = get_page_by_path($slug, OBJECT, 'post');
    if ($post) { return array('type' => 'post', 'post_id' => $post->ID); }
    // Check if it's a page
    $page = get_page_by_path($slug, OBJECT, 'page');
    if ($page) { return array('type' => 'page', 'post_id' => $page->ID); }
    return null; // Return null if no content was found
}

/* POST - Lấy Danh sách Post từ Category IDs */
function pvaPost_listByCategoryIds($catid, $limit=10, $postnotin=0, $postdate=0, $orderby='publish'){
    $args = array( 'posts_per_page' => $limit, 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => $orderby);
    if( $postnotin > 0 ){
        $args['post__not_in'] = array( $postnotin );
    }
    if( is_array($catid) ){
        $args['category__in'] = $catid;
    }else{
        $args['cat'] = $catid;
    }
    if( $postdate > 0 ){
        $args['date_query'] = array(
            //set date ranges with strings!
            'after' => date('c', $postdate - 15*86400),
            'before' => date('c', $postdate + 86400),
            //allow exact matches to be returned
            'inclusive' => true
        );
    }
    $last_posts_query = new WP_Query( $args );
    $r = array();
    while($last_posts_query->have_posts()) : 
        $last_posts_query->the_post();
        // $thumb = get_the_post_thumbnail_url('', 'square-small-thumb');
        $p = array(
            'id' => get_the_ID(),
            'permalink' => get_permalink(),
            'title' => get_the_title(),
            'date' => get_the_date(),
            'excerpt' => get_the_excerpt(),
            'thumbnail' => get_stylesheet_directory_uri().'/img/no-avatar.jpg',
            'meta' => get_post_meta(get_the_ID()),
            'content' => str_replace(']]>', ']]&gt;', apply_filters('the_content', get_the_content()))
        );
        if( !empty(get_the_post_thumbnail_url()) ){ $p['thumbnail'] = get_the_post_thumbnail_url(); }
        $image_id = get_post_thumbnail_id(get_the_ID());
        if( !empty(get_post_meta($image_id, '_wp_attachment_image_alt', true)) ){
            $p['thumbnail_alt'] = get_post_meta($image_id, '_wp_attachment_image_alt', true);
        }elseif( !empty(get_post_field('post_excerpt', $image_id)) ){
            $p['thumbnail_alt'] = get_post_field('post_excerpt', $image_id);
        }elseif( !empty(get_post_field('post_title', $image_id)) ){
            $p['thumbnail_alt'] = get_post_field('post_title', $image_id);
        }elseif( !empty(get_post_field('post_content', $image_id)) ){
            $p['thumbnail_alt'] = get_post_field('post_content', $image_id);
        }else{
            $p['thumbnail_alt'] = '';
        }
        $r[] = $p;
    endwhile;
    wp_reset_query();
    return $r;
}