Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save illucent/0748d52c0bd38d0f2767 to your computer and use it in GitHub Desktop.
Save illucent/0748d52c0bd38d0f2767 to your computer and use it in GitHub Desktop.
<?php
/*
* Template Name: AJAX Page
*
* This page template responds to the request type by serving only the content for an AJAX request
* and the content wrapped in the parent layout for a normal request. This allows for loading the
* content via AJAX and the History API without the need for hash-bang URLs.
*/
$url = rtrim($_SERVER['REQUEST_URI'],"/");
$content = "";
$subtitle = "";
$subcontent = "";
//Get the sub-content
if(have_posts()){
while(have_posts()){
the_post();
$subtitle = get_the_title();
$subcontent = get_the_content();
$subcontent = apply_filters('the_content',$subcontent);
}
}
if( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == "xmlhttprequest" ){
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(array("title" => $subtitle,"content" => $subcontent));
die();
} else {
$ancestors = get_ancestors($post->ID,'page');
if(!empty($ancestors)){
$page = get_post($ancestors[0]);
$content = $page->post_content;
$content = apply_filters('the_content',$content);
}
get_header();
echo $content;
?>
<div id='ajax-content'>
<?php echo $subcontent;?>
</div>
<?php get_footer(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment