WordPressで関連記事の表示を追加する時は、プラグインが便利でR。
特に、「Yuzo – Related Posts」は機能も豊富で便利だ二。「Yuzo – Related Posts」については、こちらを見るのでR。
しかし、
いろいろな装飾があるよりも、シンプルな機能の方がさくさくと動いているように思えるのでR。
そこで、
いろいろとソースをいじりたいのでR。
参考にしたのは、こちらでR。
しかし、
このままのソースではシンタックスエラーとなったのでR。
そこで、改良したのでR。
まず、「ダッシュボード」→「外観」→「テーマの編集」で、fuinction.phpをいじるのでR。ただし、function.phpをいじり間違えると、「サイトが….真っ白….」となるおそれもあるので、こちらの記事を参考すると良いのでR。
そのfunction.phpの最後に
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
add_image_size( 'related', 175, 125, true ); //related
}
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt);
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('/[[^]]*]/','',$excerpt);
return $excerpt;
}
を追加するのでR。
そして、
「ダッシュボード」→「外観」→「テーマの編集」で、content-single.phpを覗いて、
<?php the_content(); wp_link_pages( array( 'before' => '
<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentysixteen' ) . '</span>',
'after' => '</div>
',
'link_before' => '<span>',
'link_after' => '</span>',
'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>%',
'separator' => '<span class="screen-reader-text">, </span>',
) );
if ( '' !== get_the_author_meta( 'description' ) ) {
get_template_part( 'template-parts/biography' );
}
?>
の下に、
<?php $categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'orderby'=> rand,
'showposts'=>3, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '
<div></br>
<div>
<h3>'.__('関連記事','mythemeshop').'</h3>
</div>
<ul>';
while( $my_query->have_posts() ) {
++$counter;
if($counter == 3) {
$postclass = 'last';
$counter = 0;
} else { $postclass = ''; }
$my_query->the_post();?>
<li>
<a rel="nofollow" href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
<div>
<?php the_title(); ?>
</div>
</a>
</li>
<?php
}
echo '</ul>
</div>
';
}
}
wp_reset_query();
?>
を追加するのでR。これで、サムネイルのないタイトルのみのシンプルな関連記事が出るのでR。サムネイルがほしい場合には、さっきのソースでいけるのでR。
ただし、サムネイルありでもピリオドがついたままいまいちなのーで、それをなくすには、こちらが参考となるでR。

この記事をシェアできます。
その他の記事
-
WordPressで固定ページにウィジェットを配置するのでR ver.2
-
WordPressのランダム記事の一覧をタイトルでなく、あえて抜粋でするのでR
-
WordPressで画像の最適化を行うのでR
-
WordPressの検索にカスタム投稿も含めるのでR ver.2
-
WordPressのHTMLにおけるCSSのdisplayを理解するのでR
-
WordPressでcontent-single.phpやsingle.phpに対して特定のカテゴリーの時の条件分岐の処理を試すのでR
-
WordPressでアーカイブページのタイトルを変更するのでR
-
WordPressでブラウザーのタブにサイト名が表示されない場合の対処なのでR