Quantcast
Channel: Cat Speak
Viewing all articles
Browse latest Browse all 22

カスタム投稿タイプを固定ページとして利用する

$
0
0

WordPressのカスタム投稿タイプは、カスタムタクソノミーと合わせて利用することが一般的に浸透していますが、固定ページの階層が深くなってしまったり、役割を別に持たせたいときなんかは、カスタム投稿タイプを固定ページとして利用することができると便利ですよね。

カスタム投稿タイプを固定ページにする場合は、functions.phpに下記のように記述します。

functions.php

function add_custom() {
	register_post_type('products', array(
		'label' => '製品情報',
		'menu_position' => 5,
		'public' => true,
		'supports' => array(
			'title', 'editor','page-attributes'),
		'capability_type' => 'page',
		'hierarchical' => true
	));
	}
add_action('init', 'add_custom');

capability_type

capability_typeをpageにすると、固定ページとして利用可能になります。

page-attributes

supportsに、「page-attributes」を追加すると、管理画面から新規追加した際に、「属性」が表示され、「ページ順序」が利用できるようになります。

hierarchical

hierarchicalをtrueにすると、属性に「親」が表示され、ページに階層構造を持たせることができるようになります。

これでカスタム投稿タイプを固定ページとして利用できるようになりました。

出力の注意点

上の例では、固定ページの出力のためのテンプレートファイルとしてsingle-products.phpが利用できます。

通常の固定ページと同じように、ループ処理して出力が可能です。

single-products.php

<?php while (have_posts()) : the_post(); ?>
	<h1><?php the_title(); ?></h1>
	<div class="content">
		<?php the_content(); ?>
	</div><!--end of .content-->
<?php endwhile; ?>

また、追加したカスタム投稿タイプのナビゲーション出力は、固定ページと同様に、wp_list_pagesで行うことができます。引数post_typeに投稿タイプ名を指定します。

<?php wp_list_pages("post_type=products");?>

ただし、出力されるナビゲーションは、固定ページでは、現在のページにcurrent_page_itemというclass、現在のページの親ページにはcurrent_page_ancestorというclassがつきますが、今のところ、カスタム投稿タイプで作ったものにはclassが付きません。

下記のソースをfunctions.phpに追記しておくと、classが付与されるようになります。

functions.php

function my_page_css_class( $css_class, $page ) {
	global $post;
	if ( $post->post_parent == $page->ID )
		$css_class[] = 'current_page_ancestor';
	if ( $post->ID == $page->ID ) {
		$css_class[] = 'current_page_item';
	}
	return $css_class;
}
add_filter( 'page_css_class', 'my_page_css_class', 10, 2 );

どうやらバグのようなので、そのうちバージョンアップで改善されそうですね。

参考:http://core.trac.wordpress.org/ticket/17590


Viewing all articles
Browse latest Browse all 22

Trending Articles