HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux ubuntu-s-2vcpu-4gb-amd-sfo3-01 6.8.0-71-generic #71-Ubuntu SMP PREEMPT_DYNAMIC Tue Jul 22 16:52:38 UTC 2025 x86_64
User: root (0)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: /var/www/americahealthline.com/wp-content/themes/americahealthhaven/functions.php
<?php

// Register Custom Navigation Walker
require_once('wp_bootstrap_navwalker.php');
function register_my_menus() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Header Menu' ),
      'mobile-menu' => __( 'Mobile Menu' ), 
      'footer-menu' => __( 'Footer Menu' ), 
    )
  );
}
add_action( 'init', 'register_my_menus' );  
add_theme_support( 'post-thumbnails' );

/*------start-Custom-logo------*/
function themename_custom_logo_setup() {
    $defaults = array(
        'height'               => 100,
        'width'                => 400,
        'flex-height'          => true,
        'flex-width'           => true,
        'header-text'          => array( 'site-title', 'site-description' ),
        'link-homepage-logo' => true, 
    );
 
    add_theme_support( 'custom-logo', $defaults );
}
 
add_action( 'after_setup_theme', 'themename_custom_logo_setup' );
/**------end-Custom-logo------*/
/**
* Registers a new post type
* @uses $wp_post_types Inserts new post type object into the list
*
* @param string  Post type key, must not exceed 20 characters
* @param array|string  See optional args description above.
* @return object|WP_Error the registered post type object, or an error object
*/
if( function_exists('acf_add_options_page') ) {
	
	acf_add_options_page(array(
		'page_title' 	=> 'Theme General Settings',
		'menu_title'	=> 'Theme Settings',
		'menu_slug' 	=> 'theme-general-settings',
		'capability'	=> 'edit_posts',
		'redirect'		=> false
	));
	
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Theme Header Settings',
		'menu_title'	=> 'Header',
		'parent_slug'	=> 'theme-general-settings',
	));
	
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Theme Footer Settings',
		'menu_title'	=> 'Footer',
		'parent_slug'	=> 'theme-general-settings',
	));
}
add_action( 'init', 'testimonial' );
function testimonial() {
	$labels = array(
		'name'               => _x( 'Testimonial', 'post type general name', 'your-plugin-textdomain' ),
		'singular_name'      => _x( 'Testimonial', 'post type singular name', 'your-plugin-textdomain' ),
		'menu_name'          => _x( 'Testimonial', 'admin menu', 'your-plugin-textdomain' ),
		'name_admin_bar'     => _x( 'Testimonial', 'add new on admin bar', 'your-plugin-textdomain' ),
		'add_new'            => _x( 'Add New', 'Testimonial', 'your-plugin-textdomain' ),
		'add_new_item'       => __( 'Add New Testimonial', 'your-plugin-textdomain' ),
		'new_item'           => __( 'New Testimonial', 'your-plugin-textdomain' ),
		'edit_item'          => __( 'Edit Testimonial', 'your-plugin-textdomain' ),
		'view_item'          => __( 'View Testimonial', 'your-plugin-textdomain' ),
		'all_items'          => __( 'All Testimonial', 'your-plugin-textdomain' ),
		'search_items'       => __( 'Search Testimonial', 'your-plugin-textdomain' ),
		'parent_item_colon'  => __( 'Parent Testimonial', 'your-plugin-textdomain' ),
		'not_found'          => __( 'No Testimonial found.', 'your-plugin-textdomain' ),
		'not_found_in_trash' => __( 'No Testimonial found in Trash.', 'your-plugin-textdomain' )
	);
	$args = array(
		'labels'             => $labels,
        'description'        => __( 'Description.', 'your-plugin-textdomain' ),
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'testimonial' ),
		'capability_type'    => 'post',
		'has_archive'        => true,
		'hierarchical'       => false,
		'menu_position'      => null,
		'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
	);
register_post_type( 'testimonial', $args );
 }

 function xz_custom_post_type_init() {
    $xz_cust_post_argu = '';
    $xz_cust_post_argu = array(
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'show_in_nav_menus'  => true,
            'query_var'          => true,
            'has_archive'        => true,
            'hierarchical'       => true,
            'menu_position'      => null,
            'menu_icon'          => null,
            'supports'           => array( 'title', 'editor' )
        );

 register_post_type(
    'services', array(
      'labels' => array('name' => __( 'Services' ), 'singular_name' => __( 'services' ) ),
      'hierarchical' => true,
        'public' => true,
        'rewrite' => array(
            'slug'       => 'services',
            'with_front' => false,
        ),
      'menu_icon' => 'dashicons-admin-site',
      'has_archive' => true,
      'parent' => 'Services',
      'supports' => array('page-attributes','title', 'editor', 'thumbnail', 'comments', 'excerpt'),
      $xz_cust_post_argu,
    )
  );  
  
}
add_action( 'init', 'xz_custom_post_type_init' );


function ac_custom_post_type_init() {
    $ac_cust_post_argu = '';
    $ac_cust_post_argu = array(
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'show_in_nav_menus'  => true,
            'query_var'          => true,
            'has_archive'        => true,
            'hierarchical'       => true,
            'menu_position'      => null,
            'menu_icon'          => null,
            'supports'           => array( 'title', 'editor' )
        );

     
  register_post_type(
    'project', array(
      'labels' => array('name' => __( 'Our Projects' ), 'singular_name' => __( 'project' ) ),
      'hierarchical' => true,
        'public' => true,
        'rewrite' => array(
            'slug'       => 'project',
            'with_front' => false,
        ),
      'menu_icon' => 'dashicons-admin-site',
      'has_archive' => true,
      'parent' => 'Projects',
      'supports' => array('page-attributes','title', 'editor', 'thumbnail', 'comments', 'excerpt'),
      $ac_cust_post_argu,
    )
  );  
  
}
add_action( 'init', 'ac_custom_post_type_init' );


 /*********************li class add**********************/
add_filter ( 'nav_menu_css_class', 'so_37823371_menu_item_class', 10, 4 );
function so_37823371_menu_item_class ( $classes, $item, $args, $depth ){
  $classes[] = 'page_item current_page_item active';
  return $classes;
}
/****************li a class add******************/
function add_link_atts($atts) {
  $atts['class'] = "nav-link";
  return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_link_atts');
/****************Active class********************/
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class ($classes, $item) {
    if (in_array('current-menu-item', $classes) ){
        $classes[] = 'nav-item active';
    }
    return $classes;
}
function change_submenu_class($menu) {  
  $menu = preg_replace('/ class="sub-menu"/','/ class="sub-menu" /',$menu);  
  return $menu;  
}  
add_filter('wp_nav_menu','change_submenu_class');

/*------start-Custom-footer------*/

if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Footer Widget Area 1', 'id' => 'footer-widget-area-1', 'description' => 'First footer widget area appear in the footer', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>', ));
if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Footer Widget Area 2', 'id' => 'footer-widget-area-2', 'description' => 'Second footer widget area appear in the footer', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>', ));

 if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Footer Widget Area 3', 'id' => 'footer-widget-area-3', 'description' => 'Third footer widget area appear in the footer', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>', )); 

 if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Footer Widget Area 4', 'id' => 'footer-widget-area-4', 'description' => 'Fourth footer widget area appear in the footer', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>', ));

/*------end-Custom-footer------*/
class SocialWidget extends WP_Widget
{
  function SocialWidget()
  {
    $widget_ops = array('classname' => 'SocialWidget', 'description' => 'Display Social Icons' );
    $this->WP_Widget('SocialWidget', 'Social Icons', $widget_ops);
  }

  function form($instance)
  {
    $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
    $title = $instance['title'];
?>
  <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
  }

  function update($new_instance, $old_instance)
  {
    $instance = $old_instance;
    $instance['title'] = $new_instance['title'];
    return $instance;
  }

  function widget($args, $instance)
  {
    extract($args, EXTR_SKIP);

    echo $before_widget;
    $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

    if (!empty($title))
      echo $before_title . $title . $after_title;;

    // WIDGET CODE GOES HERE
    echo "<h1>This is my new widget!</h1>";

    echo $after_widget;
  }

}
  /*** Countdown Timer Shortcode ***/
function next_event_shortcodes_init() {
  add_shortcode('next_event', 'next_event_shortcode');
}
add_action('init', 'next_event_shortcodes_init');

function next_event_shortcode ($atts = [])
{
  // normalize attribute keys to lowercase
  $atts = array_change_key_case((array)$atts, CASE_LOWER);
  if (!array_key_exists("date", $atts)) return false;

  $time_remaining = strtotime($atts['date']) - time();

  if ($time_remaining < 0) {
    $time_remaining = 0;
  }

  $total_days_remaining = ceil($time_remaining / (60 * 60 * 24));

  if ($total_days_remaining >= 7) {
    $weeks_remaining = sprintf("%02d", floor($total_days_remaining / 7));
    $days_remaining = sprintf("%02d", $total_days_remaining % 7);
  } else {
    $weeks_remaining = sprintf("%02d", 0);
    $days_remaining = sprintf("%02d", $total_days_remaining);
  }
  
  echo "
  <div class='next-event'>
    $weeks_remaining Weeks, $days_remaining Days
  </div>";
}

  add_filter("the_content", "plugin_myContentFilter");

  function plugin_myContentFilter($content)
  {
    // Take the existing content and return a subset of it
    return substr($content, 0, 20000);
  }
  function mytheme_custom_excerpt_length( $length ) {
    return 200;
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length', 999 );


add_filter( 'acf/admin/prevent_escaped_html_notice', '__return_true' );
add_filter( 'wpcf7_validate_configuration', '__return_false' );


// function load_js() {
//  wp_register_script('bootstrap.min.js',get_template_directory_uri().'/assets/js/bootstrap.min.js','all');
//  wp_enqueue_script('bootstrap.min.js');
// }
// add_action('wp_enqueue_scripts','load_js');

function mytheme_add_woocommerce_support() {
    add_theme_support( 'woocommerce' );
}

add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );

function open_meteo_forecast_widget_ny() {
    $url = "https://api.open-meteo.com/v1/forecast?latitude=40.7128&longitude=-74.0060&daily=temperature_2m_max,temperature_2m_min,weathercode&timezone=auto";
    $response = wp_remote_get($url);

    if (is_wp_error($response)) return 'Weather data unavailable.';
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (empty($data['daily']['time'])) return 'No forecast found.';

    // Basic weather code to icon mapping
    $icons = [
        0 => '☀️', 1 => '🌤️', 2 => '⛅', 3 => '☁️', 45 => '🌫️', 48 => '🌫️',
        51 => '🌦️', 61 => '🌧️', 63 => '🌧️', 65 => '🌧️', 80 => '🌧️', 95 => '⛈️'
    ];

    $output = '<div class="weather-widget"><h4>📍 New York</h4><div class="weather-days">';
    for ($i = 0; $i < 4; $i++) {
        $date = date("D", strtotime($data['daily']['time'][$i])); // e.g. Mon, Tue
        $max = round($data['daily']['temperature_2m_max'][$i]);
        $min = round($data['daily']['temperature_2m_min'][$i]);
        $code = $data['daily']['weathercode'][$i];
        $icon = isset($icons[$code]) ? $icons[$code] : '🌡️';

        $output .= "<div class='day'>
            <div class='label'>$date</div>
            <div class='icon'>$icon</div>
            <div class='temp'><strong>$max°</strong> <span>$min°</span></div>
        </div>";
    }
    $output .= '</div><a class="see-more" href="https://www.accuweather.com/en/us/new-york/10007/weather-forecast/349727" target="_blank">See more</a></div>';
    return $output;
}
add_shortcode('weather_forecast_ny', 'open_meteo_forecast_widget_ny');

function display_trending_json() {
    $file_path = ABSPATH . 'wp-content/json-data/trending.json';

    // Debug: Check if file exists
    if (!file_exists($file_path)) {
        return '<p>❗ trending.json file not found at: ' . $file_path . '</p>';
    }

    $content = file_get_contents($file_path);
    $data = json_decode($content, true);

    // Debug: Check if JSON decoding failed
    if (json_last_error() !== JSON_ERROR_NONE) {
        return '<p>⚠️ Invalid JSON format in file.</p>';
    }

    if (!isset($data['trending']) || empty($data['trending'])) {
        return '<p>📭 No trends found inside the JSON file.</p>';
    }

    $output = '<ul class="google-trends">';
    foreach ($data['trending'] as $trend) {
        $query = urlencode($trend);
        $output .= "<li><a href='https://www.google.com/search?q={$query}' target='_blank'>{$trend}</a></li>";
    }
    $output .= '</ul>';

    return $output;
}
add_shortcode('trending_display', 'display_trending_json');

function save_sample_trending_json() {
    $data = [
        'trending' => ['AI', 'OpenAI', 'Google Trends', 'WordPress', 'Bitcoin']
    ];

    $file_path = ABSPATH . 'wp-content/json-data/trending.json';

    if (!file_exists(dirname($file_path))) {
        mkdir(dirname($file_path), 0755, true);
    }

    file_put_contents($file_path, json_encode($data, JSON_PRETTY_PRINT));
}
add_action('init', 'save_sample_trending_json'); // REMOVE after file is created


function display_trending_headlines_box() {
    $api_key = 'c9aec05df825488591385dfbc5fd7f88'; // Replace with your own key
    $api_url = "https://newsapi.org/v2/top-headlines?country=us&pageSize=10&apiKey={$api_key}";

    $args = array(
        'headers' => array(
            'User-Agent' => 'MyWordPressNewsWidget/1.0 (+https://wordpressc.goigi.biz/americahealthhaven/)',
        )
    );

    $response = wp_remote_get($api_url, $args);

    if (is_wp_error($response)) {
        return '<p>⚠️ Unable to fetch news.</p>';
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    if (isset($data['status']) && $data['status'] !== 'ok') {
        return '<p>⚠️ API Error: ' . esc_html($data['message']) . '</p>';
    }

    if (empty($data['articles'])) {
        return '<p>📭 No trending headlines available.</p>';
    }

    $output = '<div class="trend-widget">';
    // $output .= '<h4><span class="trend-icon">▮</span> Trending Now</h4><ol>';
    foreach ($data['articles'] as $article) {
        $title = esc_html($article['title']);
        $url = esc_url($article['url']);
        $output .= "<li><a href='{$url}' target='_blank'>{$title}</a></li>";
    }
    $output .= '</ol></div>';

    return $output;
}
add_shortcode('trend_box', 'display_trending_headlines_box');



add_action('wp', 'schedule_trending_news_refresh');
function schedule_trending_news_refresh() {
    if (!wp_next_scheduled('refresh_trending_news')) {
        wp_schedule_event(time(), 'hourly', 'refresh_trending_news');
    }
}
add_action('refresh_trending_news', 'display_trending_headlines_box');

function get_latest_tweets_by_userid($user_id = '31187736', $count = 2) {
    $bearer_token = 'AAAAAAAAAAAAAAAAAAAAABjj2wEAAAAAHtKfmGLQgI1J5m1TLlxuAeLR9iw=bygpdDRSEOtB8N3Cbj61wvZkI2n8K16dx1x6r20mZ1hX3xooH8';

    $url = "https://api.twitter.com/2/users/{$user_id}/tweets?max_results={$count}&tweet.fields=created_at";

    $args = array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $bearer_token,
        )
    );

    $response = wp_remote_get($url, $args);

    if (is_wp_error($response)) {
        return 'Error fetching tweets.';
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // 🐞 DEBUG START
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    // 🐞 DEBUG END

    if (empty($data['data'])) {
        return 'No tweets found.';
    }

    // Format tweets
    $output = '<ul class="twitter-feed">';
    foreach ($data['data'] as $tweet) {
        $output .= '<li>' . esc_html($tweet['text']) . '<br><small>' . esc_html($tweet['created_at']) . '</small></li>';
    }
    $output .= '</ul>';

    return $output;
}


add_shortcode('twitter_feed_id', function($atts) {
    $atts = shortcode_atts(array(
        'user_id' => '31187736',
        'count' => 5
    ), $atts);

    return get_latest_tweets_by_userid($atts['user_id'], $atts['count']);
});

function add_post_body_class($classes) {
    if (is_single() && get_post_type() === 'post') {
        $classes[] = 'is-blog-post';
    }
    return $classes;
}
add_filter('body_class', 'add_post_body_class');

function custom_alphabet_filter_shortcode() {
    ob_start();
    ?>
    <?php
    // Define post types you want to include
    $post_types = ['post', 'page', 'threads', 'track'];

    // Get all posts for the selected post types
    $args = [
        'post_type'      => $post_types,
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'orderby'        => 'title',
        'order'          => 'ASC',
    ];
    $all_posts = get_posts($args);

    // Create an array to group posts by first letter
    $alphabet_posts = [];
    foreach ($all_posts as $post) {
        $first_letter = strtoupper(substr($post->post_title, 0, 1));
        if (!preg_match('/[A-Z]/', $first_letter)) {
            $first_letter = '#'; // Non-alphabetic
        }
        $alphabet_posts[$first_letter][] = $post;
    }
    ksort($alphabet_posts);
    ?>

    <div id="custom-alphabet-filter">
        <div class="alphabet-letters">
            <?php
            foreach (range('A', 'Z') as $letter) {
                $class = isset($alphabet_posts[$letter]) ? 'has-posts' : 'no-posts';
                echo '<span class="alphabet-letter ' . $class . '" data-letter="' . $letter . '">' . $letter . '</span>';
            }
            if (isset($alphabet_posts['#'])) {
                echo '<span class="alphabet-letter has-posts" data-letter="#">#</span>';
            }
            ?>
        </div>

        <div class="alphabet-posts">
            <?php foreach ($alphabet_posts as $letter => $posts): ?>
                <div class="letter-section" id="letter-<?php echo esc_attr($letter); ?>">
                    <h3 class="letter-title"><?php echo esc_html($letter); ?></h3>
                    <ul>
                        <?php foreach ($posts as $post): ?>
                            <li>
                                <a href="<?php echo get_permalink($post->ID); ?>">
                                    <?php echo get_the_title($post->ID); ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const letters = document.querySelectorAll('.alphabet-letter');
        const sections = document.querySelectorAll('.letter-section');

        letters.forEach(letter => {
            letter.addEventListener('click', () => {
                const target = letter.dataset.letter;
                sections.forEach(sec => sec.style.display = 'none');
                const section = document.getElementById('letter-' + target);
                if (section) section.style.display = 'block';
                section.scrollIntoView({ behavior: 'smooth' });
            });
        });
    });
    </script>

    <style>
    #custom-alphabet-filter {
        font-family: sans-serif;
    }
    .alphabet-letters {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 20px;
    }
    .alphabet-letter {
        cursor: pointer;
        padding: 5px 10px;
        margin: 2px;
        border: 1px solid #ccc;
        border-radius: 4px;
        font-weight: bold;
        transition: all 0.2s;
        background: #fff;
    }
    .alphabet-letter.has-posts:hover {
        background-color: #0073AA;
        color: #fff;
    }
    .alphabet-letter.no-posts {
        opacity: 0.3;
        cursor: not-allowed;
    }
    .letter-section {
        display: none;
        margin-bottom: 20px;
    }
    .letter-section ul {
        list-style: none;
        padding-left: 0;
    }
    .letter-section li {
        margin: 5px 0;
    }
    .letter-section ul li a {
        color: #000000;
        text-decoration: none;
    }
    .letter-section ul li a:hover {
        text-decoration: underline;
    }
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('alphabet_filter', 'custom_alphabet_filter_shortcode');


add_action( 'wp_ajax_auto_thread_search', 'auto_thread_search' );
add_action( 'wp_ajax_nopriv_auto_thread_search', 'auto_thread_search' );

function auto_thread_search() {

    $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : '';

    if ( strlen($keyword) < 1 ) {
        wp_die();
    }

    $args = [
        'post_type'      => 'post',
        's'              => $keyword,
        'posts_per_page' => 10,
        'post_status'    => 'publish',
    ];

    $query = new WP_Query($args);

    if ( $query->have_posts() ) {
        echo '<ul class="auto-search-list">';
        while ( $query->have_posts() ) {
            $query->the_post();
            echo '<li>
                    <a href="'. esc_url(get_permalink()) .'">
                        '. esc_html(get_the_title()) .'
                    </a>
                  </li>';
        }
        echo '</ul>';
    } else {
        echo '<div class="no-results">No matching threads found</div>';
    }

    wp_reset_postdata();
    wp_die();
}