ワードプレス勉強用 投稿記事に関連記事を表示する方法
WPの投稿記事に関連記事を表示する方法
■関連記事を表示する方法
関連記事をプラグインを使わずに表示する!WordPress高速化Tips! - ウェブソク
■関連記事に同じカテゴリーの記事を使う場合
<?php
// カテゴリーを使う場合はこちら
$categories
= wp_get_post_categories(
$post
->ID,
array
(
'orderby'
=>
'rand'
));
// 複数カテゴリーを持つ場合ランダムで取得
if
(
$categories
) {
$args
=
array
(
'category__in'
=>
array
(
$categories
[0]),
// カテゴリーのIDで記事を取得
'post__not_in'
=>
array
(
$post
->ID),
// 表示している記事を除く
'showposts'
=>3,
// 取得記事数
'caller_get_posts'
=>1,
// 取得した記事の何番目から表示するか
'orderby'
=>
'rand'
// 記事をランダムで取得
);
$my_query
=
new
WP_Query(
$args
);
if
(
$my_query
->have_posts() ) { ?>
<ul>
<?php
while
(
$my_query
->have_posts()) :
$my_query
->the_post(); ?>
<li><?php the_post_thumbnail(
array
(100,100)); ?>
<p><a href=
"<?php the_permalink(); ?>"
title=
"<?php the_title_attribute(); ?>"
><?php the_title(); ?></a></p></li>
<?php
endwhile
;
}
wp_reset_query();
}
?>
</ul>
■関連記事に同じタグの記事を使う場合
<?php
// タグを使う場合はこちら
$tags
= wp_get_post_tags(
$post
->ID,
array
(
'orderby'
=>
'rand'
));
// 複数タグを持つ場合ランダムで取得
if
(
$tags
) {
$first_tag
=
$tags
[0]->term_id;
$args
=
array
(
'tag__in'
=>
array
(
$first_tag
),
// タグのIDで記事を取得
'post__not_in'
=>
array
(
$post
->ID),
// 表示している記事を除く
'showposts'
=>3,
// 取得記事数
'caller_get_posts'
=>1,
// 取得した記事の何番目から表示するか
'orderby'
=>
'rand'
// 記事をランダムで取得
);
$my_query
=
new
WP_Query(
$args
);
if
(
$my_query
->have_posts() ) { ?>
<ul>
<?php
while
(
$my_query
->have_posts()) :
$my_query
->the_post(); ?>
<li><?php the_post_thumbnail(
array
(100,100)); ?>
<p><a href=
"<?php the_permalink(); ?>"
title=
"<?php the_title_attribute(); ?>"
><?php the_title(); ?></a></p></li>
<?php
endwhile
;
}
wp_reset_query();
}
?>
</ul>