WordPress Ajax check for archive page

In WordPress, I need to use different layouts depending on if I am on an archive or single post page. However, my plugin code is run from the single post template, content.php.

On page load my initial check if on an archive page, is_archive(), inside the pre_get_posts filter returns TRUE but as I load the new post data using Ajax is_archive == FALSE. This makes sense as the Ajax is just querying the post data outside of any template hierarchy.

Read More

I am wondering if there is a way to hold some persistent data to let my plugin known that each post is currently on an archive page and not a single post page/template.

content.php

do_action('init-my-plugin'); 

Plugin Code

add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
public function pre_get_posts( $query ) {

    if ( !is_admin() && $query->is_main_query() ) {
        $this->is_archive = false;
        if ( is_archive() || is_home() || is_post_type_archive() ) {
            $this->is_archive = true;
        }
    }
}
// Later on in my code
if ($this->is_archive) {
    $this->layout1();
}
else {
    $this->layout2();
}

jquery

// Click event handler: Initiate Ajax request
$(document).on("click", '.nav a', function(e) { 
    e.preventDefault();
    $this = $(this);
    link = $this.attr('href');
    $.post( link, function(data) {
        // Do something with new Post Data
        var post = $(data);
    });
}); 

Related posts

Leave a Reply