当テーマでは、ブログ記事の関連記事出力はウィジェット化して、外観→ウィジェットで気軽に場所を変える事が出来るようになってます。
勿論ショートコードでも楽なんですが、ウィジェットのがもっと楽です。
で、その作り方でも
広告
関連記事をウィジェットで作るよ
ソースはこんな感じ。
class My_Widget1 extends WP_Widget {
function __construct() {
$widget_ops = array('description' => 'リフルズ関連記事');
parent::__construct(
false,
'リフルズ関連記事',
$widget_ops
);
}
function widget($args, $instance) {
?>
<?php
global $post;
$cat_now = get_the_category();
$nowid = get_the_ID();
$nowcat_id = array();
foreach($cat_now as $cat):
array_push( $nowcat_id, $cat -> cat_ID);
endforeach ;
$related_items = get_posts( array(
'post_type' => 'post',
'category__in' => $nowcat_id,
'posts_per_page' => '6',
'exclude' => $nowid,
'orderby' => 'rand'
)); ?>
<?php if ( $related_items ) : ?>
<h3 class="relatedneme"><i class="fa fa-wordpress"></i>関連記事</h3>
<ul class="related-list">
<?php foreach( $related_items as $post ): setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php if( has_post_thumbnail()) : ?>
<?php
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id, true);
$image_caption = get_post(get_post_thumbnail_id())->post_excerpt;
$image_description = get_post(get_post_thumbnail_id())->post_content;
?>
<article class="related-box" style="background:url(<?php echo $image_url[0]; ?>) no-repeat 50% 50% / auto 100%;"></article>
<?php else: ?>
<i class="fa fa-wordpress"></i>
<?php endif; ?>
<h2><?php the_title() ; ?></h2>
</a>
</li>
<?php endforeach; wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
<?php
}
function update($new_instance, $old_instance) {
return $new_instance;
}
function form($instance) {
}
}
add_action('widgets_init',create_function('', 'return register_widget("My_Widget1");'));
テーマに書いたコードのコピペなんで、要所要所かえると良い感じになります。
各場所はfunction.phpです。
内容は、ウィジェット作りますよ的な中に、必要なコードです。
関連記事出力のコードは↑の場合カテゴリーベース。
この場合、属してるカテゴリ全部取得して、同カテゴリの記事を集めます。
商品の場合、もう少しコードを変えてます。
タグベースならは、また書き方が変わります。
余談ですが、上のコードで少し面白いのはアイキャッチから画像URLを拾って、バックグラウンドに画像を置いてるトコロ。
CSSの調整がチョット複雑だけど、結構都合良いの出来るんですよ。
で上のコードを設置したら、お好みのサイドバー等に置くか、新たにサイドバーを設置してそこに置くか って感じです。
ではー
おすすめのコンテンツ
広告
