$post = NULL with ajax request
-
Hi
I am building a filtering function that does an ajax request that uses get_posts to fetch correct posts from the database. My problem is that the $post variable is null which means i cant enter the loop to get my posts.
These functions are written in functions.php:
function ajax_filter_posts_scripts() { // Enqueue script wp_register_script('afp_script', get_stylesheet_directory_uri() . '/filter-ajax.js', false, null, false); wp_enqueue_script('afp_script'); wp_localize_script( 'afp_script', 'afp_vars', array( 'afp_nonce' => wp_create_nonce( 'afp_nonce' ), 'afp_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); function ajax_filter_get_posts( $area ) { global $post; $cat_IDs = array( 'coming' => 44, 'reference' => 45, 'sold' => 46, 'sleeping' => 47, 'for_sale' => 48 ); $area = $_POST['area']; // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $for_sale_args = array( 'post_type' => 'objekt', 'category' =>$cat_IDs['for_sale'], 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'gw_search_tag', 'value' => $area, 'compare' => 'LIKE' ) ), 'order' => 'DESC' ); // If area is not set, remove key from array and get all posts if( !$area ) { unset( $for_sale_args['meta_query'] ); } if ( have_posts() ) : while ( have_posts() ) : the_post(); $for_sale_posts = get_posts($for_sale_args); foreach ( $for_sale_posts as $post ) : setup_postdata( $post );?> <!-- html stuff --> <?php endforeach; wp_reset_postdata(); endwhile; endif; die(); } add_action('wp_ajax_filter_posts','ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');And in my ajax-filter.js:
jQuery(document).ready(function($) { $body = $("body"); $(document).on({ ajaxStart: function() { $body.addClass("ajax-loading"); }, ajaxStop: function() { $body.removeClass("ajax-loading"); } }); $('#filter li').click( function(event) { // Prevent defualt action - opening tag page if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } // Get tag slug from title attirbute var selected_area = $(this).attr('area'); console.log(selected_area); $('#list').fadeOut(); data = { action: 'filter_posts', // function to execute afp_nonce: afp_vars.afp_nonce, // wp_nonce area: selected_area, // selected tag }; $.post( afp_vars.afp_ajax_url, data, function(response) { if( response ) { // Display posts on page $('#list').html( response ); // Restore div visibility $('#list').fadeIn(); } }); }); });I read somewhere that i needed to do
require_once('./wp-blog-header.php');but that didn’t work either.
How can I retrieve the $post variable? Or is it something else that I am doing wrong?
Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
The topic ‘$post = NULL with ajax request’ is closed to new replies.