【SANGO】関連記事がランダムで表示されるウィジェットの作り方

SANGOには記事のフッターに関連記事が表示されますがこれをウィジェットで表示させる方法をご紹介します。記事下のフッターに表示される記事とは別の記事が出力されますがご了承ください。

このウィジェットは記事ページやカテゴリーページに表示されそのカテゴリーに属している記事がランダムで出力されます。SANGOの関連記事機能とほとんど同じ仕様です。

実際この記事のサイドバーにランダムウィジェットを設置しているので再読み込みをして動作を確認してみてください。記事の表示数もウィジェットから設定可能です。SANGO以外でもclass名などを調整すれば使えるかもしれませんが一部SANGOの独自関数を使用しているので注意が必要です。

実装方法

カスタマイズは自己責任で

コードの追記は必ず子テーマで行いましょう。またコードに不具合やご自身のミスなどによる不具合の保証はしませんのでご注意ください。

全体のコード

functions.phpに以下のコードを貼り付けてみてください。恐らくこれでほとんどの場合動作するはずです。
表示する場所を変更したい場合は<?php if ( is_single() || is_category() && have_posts()) : ?>を変更してください。

そうするとウィジェットが増えているはずです。好きな所に配置しましょう。

functions.php
// 関連記事ウィジェット
class Related_article_Widget extends WP_Widget {
  
  public function __construct() {
    $widget_options = array(
      'description'                   => '関連記事をランダムで出力するウィジェットです。',
    );
    parent::__construct(false, $name = '関連記事', $widget_options);
  }

  public function widget($args, $instance) {
    extract($args);
    $title = apply_filters('widget_title', $instance['title']);
    $entry_num = apply_filters('widget_body', $instance['count']);
    $posts = get_related_posts($entry_num);
    if (!$posts) return;
  ?>
     <?php if ( is_single() || is_category() && have_posts()) : ?>
  <div class="widget related_article">
    <?php if ($title) echo $before_title . $title . $after_title; ?>
    <ul class="my-widget">
    <?php foreach ($posts as $post): ?>
      <li>
        <a href="<?php echo get_permalink($post->ID); ?>">
          <?php if (has_post_thumbnail($post->ID)): ?>
            <figure class="my-widget__img">
              <img width="160" height="160" src="<?php echo get_the_post_thumbnail_url($post->ID, 'thumb-160'); ?>" alt="<?php echo $post->post_title; ?>" <?php sng_lazy_attr(); ?>>
            </figure>
          <?php elseif(get_option('show_default_thumb_on_widget_posts')) :?>
            <figure class="my-widget__img">
              <img width="160" height="160" src="<?php echo featured_image_src('thumb-160', $post->ID ) ?>" <?php sng_lazy_attr(); ?>>
            </figure>
          <?php endif;?>
          <div class="my-widget__text">
            <?php echo $post->post_title; ?>
            <span class="post-date dfont"><?php echo get_the_time("Y/m/d", $val); ?></span>
          </div>
        </a>
      </li>
      <?php endforeach;?>
      <?php wp_reset_postdata();?>
    </ul>
  </div>
  <?php endif; ?>    
  <?php 
    } // END public function widget

    public function update($new_instance, $old_instance) {
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['count'] = $new_instance['count'];
      return $instance;
    } // END public function update

    public function form($instance) {
      $title = isset($instance['title']) ? esc_attr($instance['title']) : '';
      $entry_num = isset($instance['count']) ? $instance['count'] : '';
    ?>
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">タイトル:</label>
        <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
      </p>
      <p>
        <label for="<?php echo $this->get_field_id('count'); ?>">表示する記事数</label>
        <input class="tiny-text" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" type="number" step="1" min="1" value="<?php echo $entry_num; ?>" size="3">
      </p>
    <?php
  } // END public function form
}
add_action('widgets_init', function () {
  register_widget('Related_article_Widget');
});

function get_related_posts($num = 6) {
  if( has_category() ) {
    $cats = get_the_category();
    $catkwds = array();
    foreach($cats as $cat) {
        $catkwds[] = $cat->term_id;
    }
}
  return get_posts(array(
    'post_type' => 'post',
    'numberposts' => $num,
    'category__in' => $catkwds,
    'post__not_in' => array( $post->ID ),
    'orderby' => 'rand',
  ));
}
// END 関連記事ウィジェット

CSSで整える

アイコンとフッターウィジェットで使用する場合は以下のCSSを追加してください。
アイコンはfontawesomeを使用しています。ご自身で好きなアイコンに変更も可能です。

style.css
.footer .related_article {
  margin: 1.5em 0 3em;
  background: transparent;
}

.sidebar .related_article .widgettitle:before {
    content: "\f074";
}

参考記事