Skip to content

Instantly share code, notes, and snippets.

@kodie
Last active August 27, 2020 19:55
Show Gist options
  • Save kodie/4eb685328868466d218457cbcb0b4e01 to your computer and use it in GitHub Desktop.
Save kodie/4eb685328868466d218457cbcb0b4e01 to your computer and use it in GitHub Desktop.
Allows for a custom post detail page in WordPress
<?php
// Allows for a custom post detail page
add_action('init', 'hm_alternative_post_page');
function alternative_post_page() {
add_rewrite_rule('story/([^/]+)/?$', 'index.php?page_id=13317&child_post_name=$matches[1]', 'top');
}
// Setup our custom `child_post_slug` query var for custom post detail pages
add_filter('query_vars', 'alternative_post_page_var');
function hm_alternative_post_page_var($vars) {
$vars[] = 'child_post_name';
return $vars;
}
// Setup child post data for custom post detail page or display 404 template if post isn't found
function setup_child_postdata() {
$child_post_query = new WP_Query(array(
'fields' => 'ids',
'name' => get_query_var('child_post_name'),
'no_found_rows' => true,
'numberposts' => 1,
'post_type' => 'story'
));
$child_post = array_shift($child_post_query->get_posts());
if (!count($child_post)) {
global $wp_query;
$wp_query->set_404();
status_header(404);
get_template_part(404);
exit();
}
setup_postdata($GLOBALS['post'] =& $child_post);
}
?>
<?php /* Template Name: Story Details */ ?>
<?php get_header(); ?>
<?php
// Store data from parent page
$parent_page_title = get_the_title();
?>
<?php setup_child_postdata(); ?>
<section>
<h1><?php the_title(); ?></h1>
<h2><?=$parent_page_title?></h2>
<?php the_content(); ?>
</section>
<?php
// Get template part with parent page data
global $wp_query;
setup_postdata($GLOBALS['post'] =& array_shift($wp_query->get_posts()));
get_template_part('templates/inc', 'sections');
?>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment