見本
AMIMOTO公式サイトの投稿で実装してる
仕様
- 記事タイトルの背景にアイキャッチ画像を使う。なければテーマで設定した画像
- 画像全体がボタン
- CSSで暗く見えるようにしておいて、マウスホバー時はちょっと明るくする
ソース
PHP
get_adjacent_post() は表示している投稿の前後の投稿の情報を取得する関数。
マークアップはお好みで。
画像をインラインスタイルシートで背景にしているのは、レスポンシブなどで当該部分のサイズが変わっても画像のトリミングが同じ見た目になるようにCSSで調整しているから。
my-post-navigation.php
<?php
if ( ! function_exists( 'my_post_navigation' ) ) :
/**
* Display navigation to next/previous set of posts when applicable.
*/
function my_post_navigation() {
$post_nav_html = '';
// ダミー画像用意しておく
$prev_post_img = get_template_directory_uri() . '/images/dummy.png';
$next_post_img = get_template_directory_uri() . '/images/dummy.png';
$prev_post = get_adjacent_post( false, '', true );
if ( is_a( $prev_post, 'WP_Post' ) ) {
if ( has_post_thumbnail( $prev_post->ID ) ) {
$prev_post_img = wp_get_attachment_image_src( get_post_thumbnail_id( $prev_post->ID ), 'large' );
$prev_post_img = $prev_post_img[0];
}
$post_nav_html .= '<div class="nav-previous">' . "\n";
$post_nav_html .= '<a href="' . get_permalink( $prev_post->ID ) . '" rel="prev" style="background-image:url(' . $prev_post_img . ')"><span class="link-text"><span class="adjacent-text">Previous</span><br>' . get_the_title( $prev_post->ID ) . '</span></a>';
$post_nav_html .= '</div>' . "\n";
}
$next_post = get_adjacent_post( false, '', false );
if ( is_a( $next_post, 'WP_Post' ) ) {
if ( has_post_thumbnail( $next_post->ID ) ) {
$next_post_img = wp_get_attachment_image_src( get_post_thumbnail_id( $next_post->ID ), 'large' );
$next_post_img = $next_post_img[0];
}
$post_nav_html .= '<div class="nav-previous">' . "\n";
$post_nav_html .= '<a href="' . get_permalink( $next_post->ID ) . '" rel="prev" style="background-image:url(' . $next_post_img . ')"><span class="link-text"><span class="adjacent-text">Next</span><br>' . get_the_title( $next_post->ID ) . '</a></span>';
$post_nav_html .= '</div>' . "\n";
}
if ( ! empty( $post_nav_html ) ) :
?>
<nav class="navigation post-navigation" role="navigation">
<h2 class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'mytheme' ); ?></h2>
<div class="nav-links">
<?php echo $post_nav_html; ?>
</div><!-- .links -->
</nav><!-- .navigation -->
<?php
endif;
}
endif;
single.php
あたりに <?php my_post_navigation(); ?>
ッて書いておけばOK。
css
hover時にopacity変えてるけど、その辺はよしなに。
background-size: cover
で画像が調整されるようにしてある。
my-post-navigation.css
.post-navigation .nav-previous a,
.post-navigation .nav-next a {
display: block;
color: white;
background: #353c3f;
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
.post-navigation .nav-previous a:hover,
.post-navigation .nav-next a:hover {
opacity: 0.9;
}
.post-navigation .nav-previous .link-text,
.post-navigation .nav-next .link-text {
padding: 20px;
display: block;
rgba(0, 0, 0, 0.5);
}