• Resolved olofiano

    (@olofiano)


    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)
  • Which line is giving you that error?

    From what I can see, I’d guess that it’s coming from this line:

    global $post;

    If that’s the case, remove that line.

    The reason behind this is that at the stage that you’re working on it there, there is no $post object as it’s never been defined anywhere in teh script. Not every request has to have a $post object behind it, and especailyl in the case of AJAX requests there’s no object to get because there’s no post content to associate the request with – unless you specifically tell it to.

    Thread Starter olofiano

    (@olofiano)

    Thanks for your input, it is indeed that line of code that gives me the error. However, since I’m trying to use get_posts that is supposed to be located inside the loop I need the $post variable to be “working”. Otherwise the loop will be neglected. Or am I wrong?

    I got it to work by using wp_Query, but the reason i don’t want to use this is that I get problems with duplicate posts, as i have multiple loops. This is easily handed with an do-not-duplicate-array of post-ids, but for that part i need $post, which i don’t have. I realize now when writing this that i probably could use get_the_ID() or something similar.

    get_posts() does not need to be inside the loop as it doesn’t use anything from any current posts. I’ve used it outside the loop many times so I’m certain that it works.

    Thread Starter olofiano

    (@olofiano)

    Thank you for you quick replies! OK, it seems I need to go through some basics again 🙂 I’ll try without the loop and come back when it’s done.

    Thread Starter olofiano

    (@olofiano)

    Works perfectly without the loop. Guess it didn’t solve my question, but the problem is gone anyway.

    Thanks for your input, very appreciated!

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘$post = NULL with ajax request’ is closed to new replies.