WordPress頻繁に利用するコード

テーマ系

利用テーマのstyle.css階層

<?php echo get_stylesheet_directory_uri();?>

投稿一覧

<?php
    $arg = [
    'post_type' => 'post', //ポストタイプを指定
    'posts_per_page' => 6, // 表示する件数
    'orderby' => 'date', // 日付でソート
    'order' => 'DESC', // DESCで最新から表示、ASCで最古から表示
    ];
    $posts = get_posts($arg); if ($posts):
?>
<div class="container">
    <?php foreach ($posts as $post) : setup_postdata($post); ?>
    <div class="box">
        <a href="<?php the_permalink(); ?>" class="link">
            <div class="box__thumbnail">
            <?php if(has_post_thumbnail()) ://アイキャッチ画像が設定されている時?>
                <?php the_post_thumbnail(); ?>
            <?php else ://設定されてない時?>
                <div class="thumbnail-noimage"></div>
            <?php endif ;?>
            </div>
            <p class="title"><?php the_title(); ?></p>
        </a>
    </div>
<?php endforeach; ?>
<?php endif; wp_reset_postdata(); ?>
</div>

メニュー

親ページと子ページをリンク付きで出力

<?php
	$parent_id = 999;//親ページのIDを数字で指定
	$args = array(
		'posts_per_page' => -1,
		'post_type' => 'page',
		'orderby' => 'menu_order', //WordPressの表示順
		'order' => 'ASC',
		'post_parent' => $parent_id,
	);
	$common_pages = new WP_Query( $args );
	echo '<ul class="menu">';
	//親ページを表示
	echo '<li class="menu__item"><a href="' . get_permalink( $parent_id ) .'">' . get_the_title( $parent_id ) . '</a></li>';
	//子ページ表示
	if( $common_pages->have_posts() ):
		while( $common_pages->have_posts() ): $common_pages->the_post();
		echo '<li class="menu__item"><a href="' . get_permalink() .'">' . get_the_title() . '</a></li>';
		endwhile;
		wp_reset_postdata();
	endif;
	echo '</ul>';
?>

投稿・固定ページなど

スラッグを取得

<?php echo get_post( get_the_ID() )->post_name;?>

WordPress

Posted by ノジリ