Skip to content

Instantly share code, notes, and snippets.

@chriskoelle
Last active August 29, 2015 14:05
Show Gist options
  • Save chriskoelle/2e86b76e62e04ed8bd28 to your computer and use it in GitHub Desktop.
Save chriskoelle/2e86b76e62e04ed8bd28 to your computer and use it in GitHub Desktop.
Allows you to use a page as a custom post type archive (similar to the "posts page" within reading settings)
<?php
class NH_Post_Type_Pages {
private $pfpt, $post_types;
function __construct() {
$this->get_post_type_pages();
add_action( 'admin_init', array(&$this, 'reading_settings_section') );
if(!is_admin() || (defined('DOING_AJAX') && DOING_AJAX)):
add_filter( 'pre_option_show_on_front', array(&$this, 'filter_show_on_front'));
add_filter( 'pre_option_page_for_posts', array(&$this, 'filter_page_for_posts'));
endif;
}
public function filter_page_for_posts($option) {
$qo = get_queried_object();
if( !is_null($qo) && in_array($qo->ID, (array) $this->pfpt) ):
global $wp_query;
$post_type = array_search($qo->ID, $this->pfpt);
$wp_query->set( 'post_type', $post_type );
query_posts(array(
'p' => $qo->ID,
'post_type' => 'page'
));
add_action('loop_start', 'wp_reset_query');
return $qo->ID;
endif;
return $option;
}
public function filter_show_on_front($option) {
$qo = get_queried_object();
if(!is_null($qo)) $option = 'page';
return $option;
}
public function reading_settings_section() {
add_settings_section( 'post_type_pages', 'Post Type Pages', null, 'reading' );
register_setting( 'reading', 'nh_post_type_pages', $this->sanitize_custom_post_type_pages);
$this->custom_post_types();
$this->settings_fields();
}
private function settings_fields() {
foreach($this->post_types as $post_type):
add_settings_field(
"{$post_type->name}_page",
$post_type->label,
'wp_dropdown_pages',
'reading',
'post_type_pages',
array(
'name' => "nh_post_type_pages[{$post_type->name}]",
'show_option_none' => __( '&mdash; Select &mdash;' ),
'option_none_value' => '0',
'selected' => $this->pfpt[$post_type->name]
)
);
endforeach;
}
private function sanitize_custom_post_type_pages($input) {
die('test');
return array_filter($input, 'ctype_digit');
}
private function custom_post_types() {
$this->post_types = get_post_types(array(
'show_ui' => true,
'public' => true,
'_builtin' => false
), 'objects');
}
public function get_post_type_pages() {
if(is_null($this->pfpt)):
$this->pfpt = get_option('nh_post_type_pages');
endif;
return $this->pfpt;
}
}
$nh_pfpt = new NH_Post_Type_Pages();
@chriskoelle
Copy link
Author

Todo

  • Add admin settings page
  • make function work for dynamically set page id
  • Figure out template hierarchy
  • Add code commenting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment