false, 'error' => 'Method not allowed' ] ); exit; } // Get action $action = isset( $_POST['action'] ) ? sanitize_text_field( $_POST['action'] ) : ''; // Route to appropriate handler switch ( $action ) { case 'apf_filter': handle_filter_request(); break; case 'apf_track_analytics': handle_analytics_request(); break; case 'apf_autocomplete': handle_autocomplete_request(); break; default: http_response_code( 400 ); echo json_encode( [ 'success' => false, 'error' => 'Invalid action' ] ); exit; } /** * Handle filter request (main filtering logic) */ function handle_filter_request() { global $wpdb; // Verify nonce $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : ''; if ( ! apf_verify_nonce( $nonce, 'asfp_nonce' ) ) { echo json_encode( [ 'success' => false, 'error' => 'Invalid nonce' ] ); exit; } // Get parameters $filter_set_id = isset( $_POST['filter_set_id'] ) ? absint( $_POST['filter_set_id'] ) : 0; $post_type = get_post_meta( $filter_set_id, '_asfp_post_type', true ); if ( ! $post_type ) { $post_type = 'post'; } $s = isset( $_POST['s'] ) ? sanitize_text_field( $_POST['s'] ) : ''; $cat = isset( $_POST['apf_cat'] ) ? sanitize_text_field( $_POST['apf_cat'] ) : ''; // Use apf_cat to match page load $tag = isset( $_POST['apf_tag'] ) ? sanitize_text_field( $_POST['apf_tag'] ) : ''; // Use apf_tag to match page load $sort = isset( $_POST['sort'] ) ? sanitize_key( $_POST['sort'] ) : 'newest'; $paged = isset( $_POST['page'] ) ? max( 1, absint( $_POST['page'] ) ) : 1; $per_page = (int) get_post_meta( $filter_set_id, '_asfp_per_page', true ); if ( $per_page <= 0 ) { $per_page = 6; } // Track user filter interactions $filters_used = []; if ( $s ) { $filters_used[] = 'search'; } if ( $cat ) { $filters_used[] = 'category'; } if ( $tag ) { $filters_used[] = 'tag'; } if ( $sort && $sort !== 'newest' ) { $filters_used[] = 'sort'; } // Only track if user actually used filters if ( ! empty( $filters_used ) ) { $blog_template = get_post_meta( $filter_set_id, '_asfp_blog_template', true ); if ( ! $blog_template ) { $blog_template = 'template1'; } require_once( dirname( __FILE__ ) . '/includes/class-asfp-analytics.php' ); $analytics = new ASFP_Analytics(); $analytics->track_filter_usage( $filter_set_id, $filters_used, $blog_template, $post_type, $s, $sort ); } $search_scope = get_post_meta( $filter_set_id, '_asfp_search_scope', true ); $match_logic = get_post_meta( $filter_set_id, '_asfp_match_logic', true ); if ( ! in_array( $match_logic, [ 'AND', 'OR' ], true ) ) { $match_logic = 'AND'; } // Build query args with performance optimizations $args = [ 'post_type' => $post_type, 'post_status' => 'publish', // Only published posts 'paged' => $paged, 'posts_per_page' => $per_page, 'ignore_sticky_posts' => true, // Don't prioritize sticky posts 'no_found_rows' => false, // We need found_rows for pagination 'update_post_meta_cache' => true, // Cache post meta for thumbnails 'update_post_term_cache' => true, // Cache terms for categories 'suppress_filters' => false, // Allow filters for search customization ]; // Sorting switch ( $sort ) { case 'oldest': $args['orderby'] = 'date'; $args['order'] = 'ASC'; break; case 'popular': // Include posts with or without post_views meta (treat missing as 0) // Use custom orderby via filter to handle NULL values as 0 $args['orderby'] = 'post_views_num'; $args['order'] = 'DESC'; // Add filter to modify SQL to include all posts and treat NULL as 0 add_filter( 'posts_join', function( $join, $query ) { global $wpdb; static $added = false; if ( ! $added && ! strpos( $join, 'post_views_meta' ) ) { $join .= " LEFT JOIN {$wpdb->postmeta} AS post_views_meta ON ({$wpdb->posts}.ID = post_views_meta.post_id AND post_views_meta.meta_key = 'post_views')"; $added = true; } return $join; }, 10, 2 ); add_filter( 'posts_orderby', function( $orderby, $query ) { if ( strpos( $orderby, 'post_views_num' ) !== false ) { // Use COALESCE to treat NULL as 0, then cast to number $orderby = "CAST(COALESCE(post_views_meta.meta_value, '0') AS UNSIGNED) DESC"; } return $orderby; }, 10, 2 ); break; case 'az': $args['orderby'] = 'title'; $args['order'] = 'ASC'; break; case 'za': $args['orderby'] = 'title'; $args['order'] = 'DESC'; break; default: $args['orderby'] = 'date'; $args['order'] = 'DESC'; } // Search if ( $s ) { $args['s'] = $s; if ( $search_scope === 'title_only' ) { add_filter( 'posts_search', 'apf_search_by_title_only', 10, 2 ); } } // Taxonomy filters $tax_query = []; if ( $cat ) { global $wpdb; // Check if $cat is numeric (ID) or string (slug) if ( is_numeric( $cat ) ) { // It's an ID $term_id = absint( $cat ); } else { // It's a slug, convert to ID $term_id = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM {$wpdb->terms} AS t INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id WHERE t.slug = %s AND tt.taxonomy = 'category' LIMIT 1", $cat ) ); } if ( $term_id ) { $tax_query[] = [ 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => (int) $term_id, ]; } } if ( $tag ) { // Check if $tag is numeric (ID) or string (slug) if ( is_numeric( $tag ) ) { // It's an ID $tag_term_id = absint( $tag ); } else { // It's a slug, convert to ID $tag_term_id = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM {$wpdb->terms} AS t INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id WHERE t.slug = %s AND tt.taxonomy = 'post_tag' LIMIT 1", $tag ) ); } if ( $tag_term_id ) { $tax_query[] = [ 'taxonomy' => 'post_tag', 'field' => 'term_id', 'terms' => (int) $tag_term_id, ]; } } // Instead of using tax_query (which doesn't work in lightweight endpoint), // use post__in with direct database query if ( ! empty( $tax_query ) ) { $post_ids = []; foreach ( $tax_query as $key => $tax ) { if ( $key === 'relation' ) continue; $term_ids = is_array( $tax['terms'] ) ? $tax['terms'] : [ $tax['terms'] ]; $taxonomy = $tax['taxonomy']; $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT tr.object_id FROM {$wpdb->term_relationships} AS tr INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN {$wpdb->posts} AS p ON tr.object_id = p.ID WHERE tt.term_id IN (" . implode( ',', array_map( 'absint', $term_ids ) ) . ") AND tt.taxonomy = %s AND p.post_status = 'publish' AND p.post_type = %s", $taxonomy, $post_type ) ); if ( empty( $post_ids ) ) { $post_ids = $ids; } else { // Apply AND/OR logic if ( $match_logic === 'AND' ) { $post_ids = array_intersect( $post_ids, $ids ); } else { $post_ids = array_unique( array_merge( $post_ids, $ids ) ); } } } if ( ! empty( $post_ids ) ) { $args['post__in'] = $post_ids; } else { // No posts match the taxonomy filter $args['post__in'] = [ 0 ]; // Force no results } } // Execute query $query = new WP_Query( $args ); // Get template settings $template_result_item = get_post_meta( $filter_set_id, '_asfp_template_result_item', true ); $blog_template = get_post_meta( $filter_set_id, '_asfp_blog_template', true ); if ( ! $blog_template ) { $blog_template = 'template1'; } // Get display settings from filter set meta (same as page load) $show_title = get_post_meta( $filter_set_id, '_asfp_show_title', true ); $show_excerpt = get_post_meta( $filter_set_id, '_asfp_show_excerpt', true ); $show_date = get_post_meta( $filter_set_id, '_asfp_show_date', true ); $show_author = get_post_meta( $filter_set_id, '_asfp_show_author', true ); $show_image = get_post_meta( $filter_set_id, '_asfp_show_image', true ); // Convert to boolean (meta returns '1' or '') $show_title = ( $show_title === '1' || $show_title === 1 || $show_title === true ); $show_excerpt = ( $show_excerpt === '1' || $show_excerpt === 1 || $show_excerpt === true ); $show_date = ( $show_date === '1' || $show_date === 1 || $show_date === true ); $show_author = ( $show_author === '1' || $show_author === 1 || $show_author === true ); $show_image = ( $show_image === '1' || $show_image === 1 || $show_image === true ); // Build HTML using same logic as page load $html = ''; $post_ids_with_status = []; // Debug: track post IDs and statuses $ajax_handler = new ASFP_Ajax(); $display_settings = [ 'show_title' => $show_title, 'show_excerpt' => $show_excerpt, 'show_date' => $show_date, 'show_author' => $show_author, 'show_image' => $show_image, 'blog_template' => $blog_template, ]; if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $post_ids_with_status[] = get_the_ID() . ' (' . get_post_status() . ')'; // Debug $html .= $ajax_handler->render_item( get_post(), $template_result_item, $display_settings ); } wp_reset_postdata(); } else { // No posts found - use custom message from settings $no_results_message = get_post_meta( $filter_set_id, '_asfp_no_results_message', true ); if ( empty( $no_results_message ) ) { $no_results_message = 'No posts found. Please try different filters.'; } $html = '
' . esc_html( $no_results_message ) . '
'; } // Build response $response = [ 'success' => true, 'html' => $html, 'status' => sprintf( 'Found %d results', $query->found_posts ), 'found_posts' => $query->found_posts, 'max_num_pages' => $query->max_num_pages, 'debug' => [ 'per_page_setting' => $per_page, 'current_page' => $paged, 'post_count' => $query->post_count, 'query_posts_per_page' => $args['posts_per_page'], 'cat_slug' => $cat, 'tag_slug' => $tag, 'has_tax_query' => ! empty( $tax_query ), 'post_ids_with_status' => $post_ids_with_status, 'query_post_status' => $args['post_status'], 'sql_query' => $query->request, ], 'current_page' => $paged, ]; echo json_encode( $response ); exit; } /** * Handle analytics tracking request */ function handle_analytics_request() { // Get analytics data $data = isset( $_POST['data'] ) ? json_decode( stripslashes( $_POST['data'] ), true ) : []; if ( empty( $data ) ) { echo json_encode( [ 'success' => false, 'error' => 'No data provided' ] ); exit; } // Send to analytics server (truly non-blocking) using cURL $analytics_url = get_option( 'apf_analytics_url', 'https://analyticsajaxfilter.rf.gd/api/analytics.php' ); // Use cURL with fire-and-forget (non-blocking) request if ( function_exists( 'curl_init' ) ) { $ch = curl_init( $analytics_url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false ); // Don't wait for response curl_setopt( $ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Connection: Close', 'Content-Length: ' . strlen( json_encode( $data ) ) ] ); curl_setopt( $ch, CURLOPT_NOSIGNAL, 1 ); // Prevent signals from interrupting curl_setopt( $ch, CURLOPT_FRESH_CONNECT, true ); // Don't reuse connections curl_setopt( $ch, CURLOPT_FORBID_REUSE, true ); // Force close connection $response = @curl_exec( $ch ); // Log response if any if ( $response !== false ) { error_log( 'Analytics response: ' . $response ); }else{ error_log( 'Analytics response else: ' ); } @curl_close( $ch ); } echo json_encode( [ 'success' => true ] ); exit; } /** * Handle autocomplete request */ function handle_autocomplete_request() { global $wpdb; // Verify nonce $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( $_POST['nonce'] ) : ''; if ( ! apf_verify_nonce( $nonce, 'asfp_nonce' ) ) { echo json_encode( [ 'success' => false, 'error' => 'Invalid nonce' ] ); exit; } $filter_set_id = isset( $_POST['filter_set_id'] ) ? absint( $_POST['filter_set_id'] ) : 0; $term = isset( $_POST['term'] ) ? sanitize_text_field( $_POST['term'] ) : ''; $post_type = get_post_meta( $filter_set_id, '_asfp_post_type', true ); if ( ! $post_type ) { $post_type = 'post'; } if ( strlen( $term ) < 2 ) { echo json_encode( [ 'success' => true, 'results' => [] ] ); exit; } // Search posts $args = [ 'post_type' => $post_type, 'post_status' => 'publish', 's' => $term, 'posts_per_page' => 5, ]; $query = new WP_Query( $args ); $results = []; if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $results[] = [ 'title' => get_the_title(), 'image' => get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' ), ]; } wp_reset_postdata(); } echo json_encode( [ 'success' => true, 'results' => $results ] ); exit; } /** * Search by title only */ function apf_search_by_title_only( $search, $wp_query ) { global $wpdb; if ( empty( $search ) ) { return $search; } $q = $wp_query->query_vars; $n = ! empty( $q['exact'] ) ? '' : '%'; $search = ''; $searchand = ''; foreach ( (array) $q['search_terms'] as $term ) { $term = esc_sql( $wpdb->esc_like( $term ) ); $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; $searchand = ' AND '; } if ( ! empty( $search ) ) { $search = " AND ({$search}) "; } return $search; }