PR

Cocoonでスニペット付き新着記事と人気記事一覧の作成ver1.8.9.3まで

この記事は約18分で読めます。
スポンサーリンク

作成の背景

ワードプレス(以下WP)の無料のテーマCocoonでは新着記事一覧と人気記事一覧を表示させるショートコードが用意されています。

カテゴリーページにおいては、当該カテゴリーに紐づく記事がアイキャッチ画像、カテゴリー名、タイトル、抜粋(スニペット)、作成日付とともに表示されるのに対して、新着/人気記事一覧のショートカットにおいては、アイキャッチ画像とタイトルだけという非常に簡素な内容になります。

これは思うにSEO対策を考えれば長いタイトルだけが表示できれば抜粋などは要らないという世の中の潮流に沿ったものになっていると思います。

ただし、本サイトではタイトルはなるべく簡潔にしたいと考えているため、標準のショートコードでは、とてもスカスカで貧相な内容になってしまうことになります。

従いまして、会社としては何とかしてカテゴリーページで表示される内容に近いものを新着/人気記事一覧でも表示させたく思い、WPの動きをつかさどるPHPプログラムの修正をすることにしました。

本来このような修正をすべきではない理由

  1. いくつかの基本的な関数を使用しているプログラムに対する改修であるため、WPのバージョンアップやCocoonのバージョンアップにより動きが変わる可能性が高い。
  2. 標準の新着/人気記事一覧のプログラムを修正するのではなく、同じようなプログラムを別途作成するため、コードが冗長化する。
    • 既存のプログラムをそのまま置き換えるためには、そのプログラムが呼ばれている箇所を全て確認する必要があり、また1であげた影響を避けることができないために、リスクが大きくなる。
  3. 世の中の潮流に載っていない。
  4. Cocoon作者である「わいひら」様自身が本機能を変更する可能性がある。

作成内容

※ここでは忘備録のために内容を記載しますが、もしも流用される場合は自己責任でお願いを致します。

子テーマのfunctions.phpにそれぞれ下記の関数を追加します。
量は多いのですが、ほぼほぼ「snipet」がつかないもともとある関数に対してほんの少し変更しただけの内容になります。
※generate_widgetsnipet_entry_card_dateは新着/人気記事一覧で同じ関数を使用します。

【追記】(2019/4/12)
下記の関数は 「cocoon-master\lib\shortcodes.php」のファイルに中に書かれています。//

new_entries_shortcodeをコピーして修正

//スニペット付き新着記事ショートコード関数
if (!shortcode_exists('newsnipet_list')) {
  add_shortcode('newsnipet_list', 'newsnipet_entries_shortcode');
}
if ( !function_exists( 'newsnipet_entries_shortcode' ) ):
function newsnipet_entries_shortcode($atts) {
  extract(shortcode_atts(array(
    'count' => 5,
    ----- 省略 -----
    'action' => null,
    'snipet' => 1,                  //←追加
  ), $atts));

  //カテゴリを配列化
  $cat_ids = array();
    ----- 省略 -----
  //引数配列のセット
  $atts = array(
    'entry_count' => $count,
    ----- 省略 -----
    'action' => $action,
    'snipet' => $snipet,            //←追加
  );
  ob_start();
  generate_widgetsnipet_entries_tag($atts);
  // generate_widgetsnipet_entries_tag($count, $type, $categories, $children, $post_type, $taxonomy, $random, $action, $snipet);         //←追加
  $res = ob_get_clean();
  return $res;
}
endif;

popular_entries_shortcodeをコピーして修正

//人気記事ショートコード関数
if (!shortcode_exists('popularsnipet_list')) {
  add_shortcode('popularsnipet_list', 'popularsnipet_entries_shortcode');
}
if ( !function_exists( 'popularsnipet_entries_shortcode' ) ):
function popularsnipet_entries_shortcode($atts) {
  extract(shortcode_atts(array(
    'days' => 'all',
    'count' => 5,
    'type' => 'default',
    'rank' => 0,
    'pv' => 0,
    'cats' => 'all',
    'snipet' => 1,                 //←追加
  ), $atts));
  $categories = array();
  if ($cats && $cats != 'all') {
    $categories = explode(',', $cats);
  }
  ob_start();
  generate_popularsnipet_entries_tag($days, $count, $type, $rank, $pv, $snipet, $categories);//←追加
  $res = ob_get_clean();
  return $res;
}
endif;

文字コード:UTF-8N 改行コード:CR+LF

【追記】(2019/4/12)下記関数は「cocoon-master\lib\html-forms.php」に書かれています。//

generate_widget_entries_tagをコピーして修正

//汎用エントリースニペット付きウィジェットのタグ生成
if ( !function_exists( 'generate_widgetsnipet_entries_tag' ) ):
// function generate_widgetsnipet_entries_tag($entry_count = 5, $entry_type = ET_DEFAULT, $cat_ids = array(), $include_children = 0, $post_type = null, $taxonomy = 'category', $random = 0, $action = null, $snipet = 1){               //←一部追加
function generate_widgetsnipet_entries_tag($atts){
  extract(shortcode_atts(array(
    'entry_count' => 5,
    ----- 省略 -----
    'action' => null,
    'snipet' => 1,                   //←追加
  ), $atts));
  //ランダムが有効な時は関連記事
    ----- 省略 -----
  ?>
  <div class="<?php echo $prefix; ?>-entry-cards widget-entry-cards no-icon cf<?php echo get_additional_widget_entriy_cards_classes($entry_type); ?>">
  <?php //if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <?php if ( $query -> have_posts() ) : while ( $query -> have_posts() ) : $query -> the_post(); ?>
  <a href="<?php the_permalink(); ?>" class="<?php echo $prefix; ?>-entry-card-link widget-entry-card-link a-wrap" title="<?php the_title(); ?>">
    <div class="<?php echo $prefix; ?>-entry-card widget-entry-card e-card cf">
      <figure class="<?php echo $prefix; ?>-entry-card-thumb widget-entry-card-thumb card-thumb">
    ----- 省略 -----
      <div class="<?php echo $prefix; ?>-entry-card-content widget-entry-card-content card-content myfont120"> <!-- class追加 -->
        <span class="<?php echo $prefix; ?>-entry-card-title widget-entry-card-title card-title"><u><?php the_title();?></u></span>

        <?php //スニペット追加  //←ここから8行追加
          if ($snipet) {
            echo '<br><br><span class="blogcard-snipet internal-blogcard-snipet">';
            echo get_the_excerpt();
            echo '</span>';
            generate_widgetsnipet_entry_card_date($prefix,get_the_ID());    //←もとあるコードを修正
          }
        ?>

      </div><!-- /.new-entry-content -->
    </div><!-- /.new-entry-card -->
  </a><!-- /.new-entry-card-link -->
  <?php endwhile;
  else :
    echo '<p>'.__( '記事は見つかりませんでした。', THEME_NAME ).'</p>';//見つからない時のメッセージ
  endif; ?>
  <?php wp_reset_postdata(); ?>
  <?php //wp_reset_query(); ?>
  </div>
<?php
}
endif;

文字コード:UTF-8N 改行コード:CR+LF

【追記】(2019/4/12)
上記コーディングに含まれている「get_additional_popular_entriy_cards_classes」関数の名称がバージョン1.7.4.4で変更になっています。
バージョン1.7.4.4以降では「get_additional_popular_entry_cards_classes」になりますのでご注意ください
//


※style.cssはCocoon子テーマにあるファイルに追記します。

.myfont120 {
  font-size: 120%;
}

【追記】(2019/4/12)下記関数は「cocoon-master\lib\html-forms.php」に書かれています。//

generate_popular_entries_tagをコピーして修正

//スニペット付き人気ランキングリストの取得
if ( !function_exists( 'generate_popularsnipet_entries_tag' ) ):
function generate_popularsnipet_entries_tag($days = 'all', $entry_count = 5, $entry_type = ET_DEFAULT, $ranking_visible = 0, $pv_visible = 0, $snipet = 1, $cat_ids = array(), $exclude_post_ids = array(), $exclude_cat_ids = array()){                 //←一部追加
  $records = get_access_ranking_records($days, $entry_count, $entry_type, $cat_ids, $exclude_post_ids, $exclude_cat_ids);

  //var_dump($records);
  $thumb_size = get_popular_entries_thumbnail_size($entry_type);
  ?>
    ----- 省略 -----
  <a href="<?php echo $permalink; ?>" class="popular-entry-card-link a-wrap no-<?php echo $i; ?>" title="<?php echo esc_attr($title); ?>">
    <div class="popular-entry-card widget-entry-card e-card cf">
      <figure class="popular-entry-card-thumb widget-entry-card-thumb card-thumb">
        <?php echo $post_thumbnail_img; ?>
        <?php the_nolink_category($post->ID, false); //カテゴリラベルの取得 ?>
      </figure><!-- /.popular-entry-card-thumb -->

      <div class="popular-entry-card-content widget-entry-card-content card-content myfont120"> <!-- class追加 -->
        <span class="popular-entry-card-title widget-entry-card-title card-title"><u><?php echo $title;?></u></span>

        <?php //スニペット追加                 //←追加開始
        if ($snipet) {
            //global $post;
            $post_data = get_post($post->ID);

            //メタディスクリプションの取得
            $snipetdata = get_the_page_meta_description($post->ID);

            //投稿管理画面の抜粋を取得
            if (!$snipetdata) {
              $snipetdata = $post_data->post_excerpt;
            }
            //All in One SEO Packのメタディスクリプションを取得
            if (!$snipetdata) {
              $snipetdata = get_the_all_in_one_seo_pack_meta_description($post->ID);
            }
            //記事本文の抜粋文を取得
            if (!$snipetdata) {
              $snipetdata = get_content_excerpt($post_data->post_content, get_entry_card_excerpt_max_length());
            }
            $snipetdata = preg_replace('/\n/', '', $snipetdata);
            $snipetdata = apply_filters( 'cocoon_blogcard_snipet', $snipetdata );
            $snipetdata = apply_filters( 'cocoon_internal_blogcard_snipet', $snipetdata );
            echo '<br><br><span class="blogcard-snipet internal-blogcard-snipet">';
            echo $snipetdata;
            echo '</span>';
          }
        ?>                        <?php                  //←追加終了 ?>

        <?php if ($pv_visible): ?>
          <span class="popular-entry-card-pv widget-entry-card-pv"><?php echo $pv == '1' ? $pv.' view' : $pv.' views';?></span>
        <?php endif ?>
        <?php generate_widgetsnipet_entry_card_date('popular', $post->ID); ?>  <?php  //←修正 ?>
      </div><!-- /.popular-entry-content -->
    </div><!-- /.popular-entry-card -->
  </a><!-- /.popular-entry-card-link -->

  <?php
  $i++;
  endforeach;
  else :
    echo '<p>'.__( '人気記事は見つかりませんでした。', THEME_NAME ).'</p>';//見つからない時のメッセージ
  endif; ?>
  </div>
<?php
}
endif;

【追記】(2019/4/12)下記関数は「cocoon-master\lib\html-forms.php」に書かれています。//

generate_widget_entry_card_dateをコピーして修正

if ( !function_exists( 'generate_widgetsnipet_entry_card_date' ) ):
function generate_widgetsnipet_entry_card_date($prefix, $post_id = null){?>
<div class="<?php echo $prefix; ?>-entry-card-date widget-entry-card-date">   <?php //←display=noneを削除 ?>
  <span class="<?php echo $prefix; ?>-entry-card-post-date widget-entry-card-post-date post-date"><?php echo get_the_time(get_site_date_format(), $post_id); ?></span><?php
    //更新日の取得
    $update_time = get_update_time(get_site_date_format(), $post_id);
  if($update_time):
  ?><span class="<?php echo $prefix; ?>-entry-card-update-date widget-entry-card-update-date post-update"><?php echo $update_time; ?></span><?php
  endif; ?>
</div><?php
}
endif;

使い方

標準の新着/人気記事一覧の使い方と同じですが、ともにsnipetの有無をオプション(引数)で指定できます。
またもともと標準で設定されているオプション(引き通)も同様に使用できます。

新着記事一覧:[newsnipet_list snipet=1] 人気記事一覧:[popularsnipet_list snipet=1]

  • snipet=1がデフォルトになるのでオプション(引数)は省略できます。
  • 上記[]は全角になっていますので、そのままコピペはできません。
新着記事一覧:[newsnipet_list snipet=0] 人気記事一覧:[popularsnipet_list snipet=0]
  • スニペットと作成日、変更日を表示しない場合
  • 上記[]は全角になっていますので、そのままコピペはできません。

以上、ご報告申し上げます。

P.S.
掲示するのが遅くなり恐縮です。
本日(2019/2/15)検索機能の確認をしていて気付いたのですが、サイドバーに表示する新着記事/人気記事一覧のスニペットの部分もワード検索での対象になるようです。(この事象はWPでの検索機能を使用する上では避けることができないと思います。)
もしも検索の精度を重視する場合は、本ページの変更をすると結果が相反しますのでご注意ください。

【追記】2019/3/6
当初新着記事一覧と人気記事一覧は別々の記事にしていましたが、冗長的な部分があるので両者を合体させました。//

【追記】2019/3/13
styleタグを「myfont120」classに変更//

【追記】2019/4/12
バージョン1.7.4.4への対応//