wordpressカスタム投稿作成
- 公開日:
- 更新日:
- 文字数:3973文字
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'news', [ // 投稿タイプ名の定義
'labels' => [
'name' => 'ニュース', // 管理画面上で表示する投稿タイプ名
'singular_name' => 'news', // カスタム投稿の識別名
],
'public' => true, // 投稿タイプをpublicにするか
'has_archive' => false, // アーカイブ機能ON/OFF
'menu_position' => 5, // 管理画面上での配置場所
'show_in_rest' => true, // 5系から出てきた新エディタ「Gutenberg」を有効にする
'supports' => array('title','editor,'thumbnail'),
]);
}
add_action( 'init', 'create_post_type' );
カスタム投稿のURL変更 プラグインを利用
カスタム投稿の情報を取得方法
トップページでの表示
<ul>
<?php
$args = array(
'post_type' => 'news',
'posts_per_page' => 4,
//'category__not_in' => array(5)
//'cat' =>1
//'orderby' => 'rand',
);
?>
<?php $the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li><time><?php the_time('Y.m.d');?></time><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></li>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
</ul>
アーカイブページ(arhive-news.php)
-
<ul> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li><time><?php the_time('Y.m.d');?></time><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></li> <?php endwhile; ?> <?php else : ?> <h2 style="padding-left:20px;">お知らせが登録されてません。</h2> <?php endif; ?> </ul> <div class="pagination"> <?php $args = array( 'prev_next' => true, 'prev_text' => '<', 'next_text' => '>', 'mid_size' =>5, ); ?> <?php echo paginate_links($args); ?> </div> <?php wp_reset_postdata(); ?>ページネーションSCSS
.pagination{ margin-top: 60px; text-align: center; width: 100%; a,span{ font-size: 16px; display: inline-block; margin: 0px 10px; @include media(md){ font-size: 18px; } } }タクソノミーの追加方法
-
- 詳しくはこちら
- https://worldofit.work/php/877/
-
Singleページ
条件分岐したい場合
if( is_singular('news') ) { }elseif(is_single()){ }<?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article class="news-article"> <div class="content-width"> <h2><?php the_title(); ?></h2> <time><?php the_time('Y.m.d');?></time> <div class="news-article-img"> <?php the_post_thumbnail(''); ?> </div> <div class="news-article-content"> <p><?php the_content(); ?></p> </div> </div> </article> <?php endwhile; ?> <?php endif; ?> <?php wp_reset_postdata(); ?>カスタム投稿タイプのアーカイブかどうかの判別
if( is_post_type_archive( 'news' ) ) { }カスタム投稿のアーカイブの記事数を変更
add_action( 'pre_get_posts', 'my_custom_query_vars' ); function my_custom_query_vars( $query ) { /* @var $query WP_Query */ if ( !is_admin() && $query->is_main_query()) { if ( is_post_type_archive('カスタム投稿タイプのスラッグ') ) { $query->set( 'posts_per_page' , 10 );//表示したい数 } } return $query; }参考
https://qiita.com/sola-msr/items/a715f02265acd4864b03
https://php1st.com/2021
- http://kawatama.net/web/1288
