概要説明
カスタム投稿をして投稿とは別の記事を登録したい時に使用するカスタマイズ。お知らせやスタッタフ紹介、制作実績、キャンペーンなど特定の用途で記事を分類したい際に利用します。
~ 目次 ~
プラグイン無しでカスタム投稿を追加 functions.php
functions.php
/*----------------------------------------------------
カスタム投稿追加
----------------------------------------------------*/
if ( !function_exists( 'add_post_type' ) ){
function add_post_type() {
// 定義設定
$slug = 'photo';
$post_type_label = 'フォトギャラリー';
$taxonomy_label = 'カテゴリー';
// カスタム投稿定義
register_post_type($slug,
array(
'label' => $post_type_label,
'description' => '',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => true,
'query_var' => false,
'has_archive' => true,
'exclude_from_search' => false,
'supports' => array(
'title', // タイトル
'editor', // 本文
'revisions', // リビジョン
'thumbnail', // アイキャッチ
),
)
);
// カスタム投稿用のカテゴリー定義
register_taxonomy(
$slug.'_cat',
$slug,
array(
'hierarchical' => true,
'label' => $taxonomy_label,
'show_ui' => true,
'query_var' => true,
'rewrite' => array('slug' => $slug),
'singular_label' => $taxonomy_label
)
);
// 他にも追加したい場合は以下に同様に定義
}
add_action( 'init', 'add_post_type' );
}
正常に追加されると管理画面のメニューが増えます
以上で管理画面側の設定は完了です
カスタム投稿記事の詳細ページを表示させる
single-カスタム投稿slug.php ( 上記例の場合は single-photo.php )
レイアウトをそのまま使いたいなら single.php をコピーして作成がオススメ。
<?php
get_header();
while ( have_posts() ) : the_post();
?>
<div><?php the_post_thumbnail('full'); ?></div>
<div><?php the_title(); ?></div>
<div><?php the_time( 'Y.m.d' ); ?></div>
<div><?php the_content(); ?></div>
<?php
// カテゴリー表示
$terms = get_the_terms($post->ID, 'photo_cat');
if ( isset($terms['0']->name) ) {
echo '<div>'.$terms['0']->name.'</div>';
}
endwhile;
get_footer();
?>
新たにページを作成する場合は上記をベースにレイアウトを反映してページを作成
カスタム投稿記事のアーカイブページを表示させる
<blockquote>archive-カスタム投稿slug.php ( 上記例の場合は archive-photo.php )</blockquote>
archive.phpまたはarchive-xxx.phpが既にある場合はコピーして作成がオススメ。
<?php
get_header();
while ( have_posts() ) : the_post();
?>
<a href="<?php the_permalink(); ?>">
<div><?php the_post_thumbnail('thumbnail'); // サムネイルサイズ ?></div>
<?php
// カテゴリー表示
$terms = get_the_terms($post->ID, 'photo_cat');
if ( isset($terms['0']->name) ) {
echo '<div>'.$terms['0']->name.'</div>';
}
?>
<div><?php echo mb_strimwidth( strip_tags( get_the_title() ), 0, 50, '...' ); // 長い場合は省略 ?></div>
<div><?php the_time( 'Y.m.d' ); ?></div>
<div><?php echo mb_strimwidth( strip_tags( get_the_content() ), 0, 100, '...' ); // 長い場合は省略 ?></div>
</a>
<?php
endwhile;
// ページネーション
$paginate_links = paginate_links( array(
'current' => max( 1, get_query_var( 'paged' ) ),
'next_text' => '',
'prev_text' => '',
'total' => $wp_query->max_num_pages,
'type' => 'array',
) );
if ( $paginate_links ) :
?>
<ul>
<?php
foreach ( $paginate_links as $paginate_link ) :
echo '<li>'.$paginate_link.'</li>';
endforeach;
?>
</ul>
<?php
endif;
get_footer();
?>



