サイトの高速化①WordpressPopularPostを止める

Wordpress Popular Postという超有名定番プラグインを使っていました。 こいつは本当に遅いです。 データベースを使います。 負荷がかかるからMixhostでも推奨されていないっぽい

だけど、表示が優秀だし、ランキングは正確だし WPP Plusという、サイドバーにカテゴリ別にランキングできる有能プラグインもあり 遅いってわかってても手放せませんでした。

でも、こんなしょぼいブログのランキングなんて誰が見るんだよと思いまして。 思い切って外しました。

長くなるので要約 [wp-svg-icons custom_icon="check-square" wrap="i"] このサイトはSimple Ga Rankingというプラグインに乗り換えた [wp-svg-icons custom_icon="check-square" wrap="i"] Lemonedの方は、プラグインを使わずにやってみた

Simple GA Ranking

代わりに、Simple GA RankingというGoogle Analyticsを使うプラグインを使用しました。

アナリティクスよりPtengineの方が好きなのですが、仕方ありませんね。

設定はこちら二つのサイトを参考にしました。

【WordPress】サーバ負荷が軽い「Simple GA Ranking」プラグインで人気記事ランキングを表示する方法 | Tips Note by TAM ワードプレスの人気記事表示プラグイン「Simple GA Ranking」の設定とサムネイル表示

functions.phpに書き入れるのですが・・・

add_filter('sga_ranking_before_title', 'showRankingImage', 10, 3);
function showRankingImage($ret, $id, $cnt) {
$post_url = get_permalink($id); // 記事のURL
$title = get_the_title($id); //タイトル
$ret = "";
if( has_post_thumbnail( $id ) ) { // アイキャッチ画像の有無
$post_thumb_src = wp_get_attachment_image_src( get_post_thumbnail_id( $id ),array( 150, 150 ) );
$post_thumb = $post_thumb_src[0];
$ret = "<div class='ranking-img'><a href=\"{$post_url}\" title=\"{$title}\"><img src=\"{$post_thumb}\" alt=\"{$title}\" title=\"{$title}\"></a></div>";
}
return $ret;
}

しかしこれだとサムネイルがサムネイルでなく原寸大サイズの画像を参照している? そんなことよりサムネイルが無い投稿はno-imageを出したいのだがどうもうまくいかない

echo get_bloginfo( 'stylesheet_directory' ) . '/images/no-image.png';

これではURLが書き出されてしまうから

echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/img/noimage.png" />';

なのはわかったけど

[wp-svg-icons custom_icon="pointer" wrap="i"] 参考 [blogcard url=”https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/has_post_thumbnail”] [blogcard url=”http://on-ze.com/archives/5621”] これだとループの位置がおかしいのかランキングの上に並んでしまう どこに挿入してもうまくいかない。くそ・・・わからん・・・ ショートコードでやる方法も動かず・・・・

とりあえずそのまま使ってます。

自作する

lemonedの方はphpショートコードでプラグイン使わずにやってみた。

自作ウィジェットに表示させるやり方。

今回はこちらを参考にいたしました。 [blogcard url=”https://manablog.org/wordpress-popular-posts-without-plugin/”]

実行部分です。sidebar.phpが分かれてたら直接記述で良い。 BootstrapのクラスだったのでGenesisのカラムクラスに変えました。サムネイルも標準サムネイル表示に。


<?php
// views post metaで記事のPV情報を取得する
setPostViews(get_the_ID());

// ループ開始
query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&order=DESC'); while(have_posts()) : the_post(); ?>

<!-- サムネイルの表示 -->
<div class="one-half first">
    <a href="<?php echo get_permalink(); ?>">
        <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'thumbnail'); } ?>
    </a>
</div>

<!-- タイトルの表示 -->
<div class="one-half">
    <p>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
    </p>
</div>

<?php endwhile; ?>

カウント取得部分はうまく動かなかったのでこちらを参考にしました。 [blogcard url=”https://ikisakianco.com/wordpress-noplugin-popular-posts”]

時間の変更

元コードは1時間で更新になってたけど1週間にしたい。

UNIX時間とか言われましても。わかるわけないので調べました。

[blogcard url=”https://popozure.info/20151021/9618”]

1週間ごとって指定できないのか

長くするためには追加すればOKとのこと

[blogcard url=”https://www.imamura.biz/blog/24596”]

wp_schedule_eventはhourly twicedaily dailyの三つからしか選べないけど cron_schedulesは自由に設定できる ってことでおk? どちらも設定して意味がよくわからん

こちらによると [blogcard url=”https://office7f.com/2015/02/05/wordpress-wp-cron/”]

ただし、この「wp_cron」は擬似的なcronで、指定した時間に必ず実行されるものではありません。

ということは、リセットの処理をwp_cronで予定して、処理を行うのをwp_schedule_eventで登録でおk? 毎日、設定したスケジュール日かを確認する、っていうイメージかな・・

そもそも、add_filterってactionとどう違うの

[blogcard url=”http://actyway.com/3750”]

ああ疲れた。

とりあえず真っ白にならないコード(funcions.php

//アクセス数をカウントする
function set_post_views() {
  $postID = get_the_ID();
  $num = (int)date_i18n('H'); // 現在時間で番号取得
  $key = 'pv_count';
  $count_key = '_pv_count';
  $count_array = get_post_meta( $postID, $count_key, true );
  $sum_count = get_post_meta( $postID, $key, true );

  if( !is_array($count_array) ) { //配列ではない
    $count_array = array();
    $count_array[$num] = 1;
  } else { //配列である
    if ( isset( $count_array[$num] ) ) { //カウント配列[n]が存在する
      $count_array[$num] += 1;
    } else { //カウント配列[n]が存在しない
      $count_array[$num] = 1;
    }
  }

  //アクセス数を更新する
  update_post_meta( $postID, $count_key, $count_array );
  update_post_meta( $postID, $key, $sum_count + 1 );
}

//アクセス数をリセットする
function reset_post_views() {
  $num = (int)date_i18n('H');
  $key = 'pv_count';
  $reset_key = '_pv_count';

  $args = array(
    'posts_per_page'   => -1,
    'post_type' => 'post',
    'post_status'=>'publish',
    'meta_key' => $reset_key,
  );

  $reset_posts = get_posts($args);
  if($reset_posts):
    foreach($reset_posts as $reset_post):
      $postID = $reset_post->ID;
      $count_array = get_post_meta( $postID , $reset_key, true );

      if ( isset( $count_array[$num] ) ) { //カウント配列[n]が存在する
        $count_array[$num] = 0;
      }

      //アクセス数をリセットする
      update_post_meta( $postID, $reset_key, $count_array );
      update_post_meta( $postID, $key, array_sum( $count_array ) );
    endforeach;
  endif;
}

//リセット関数を実行するアクションフックを追加
add_action( 'set_hours_event', 'reset_post_views' );

//実行間隔の追加
function my_interval( $schedules ) {
  // 1時間→1週間に
  $schedules['weekly'] = array(
    'interval' => 604800,
    'display' => 'every 1 weeks'
  );
  return $schedules;
}
add_filter( 'cron_schedules', 'my_interval' );

//アクションフックを定期的に実行するスケジュールイベントの追加
function my_activation() {
  if ( ! wp_next_scheduled( 'set_hours_event' ) ) {
    wp_schedule_event( time(), 'daily', 'set_hours_event' );
  }
}
add_action('wp', 'my_activation');

サイドバーウィジェットの作成

次に、サイドバーに表示したいが、実行PHPコードをウィジェットに直接書きたくないので自作ウィジェットを作成する。 (PHP Code Widgetプラグインを使わない)

ウィジェットの作り方はこちらを参考にさせていただきました [blogcard url=”http://wp.kikuchisan.net/wordpress-widget.html”]

最初のPHPコードをウィジェットのコードに融合 タイトルはウィジェットのフォームで指定とかややこしいので(変えないし)直接記述。

CSSは現在のテーマに合わせて直接記載で。


// 自作WPPウィジェット
class PP_Widget extends WP_Widget {
    function __construct() {
        parent::__construct(false,'Popular Post表示'); //ウィジェットボックスの名前
    }
   function widget($args, $instance) {
         ?>
<div class="widget-wrap">
<h4 class="widget-title widgettitle">Popular Post</h4>
<?php
// views post metaで記事のPV情報を取得する
setPostViews(get_the_ID());

// ループ開始
query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&order=DESC'); while(have_posts()) : the_post(); ?>

<!-- サムネイルの表示 -->
<div class="one-half first">
    <a href="<?php echo get_permalink(); ?>">
        <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'thumbnail'); 
        }
        else {
    echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/img/noimage.png" />';
        } ?>

    </a>
</div>

<!-- タイトルの表示 -->
<div class="one-half">
    <p>
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
    </p>
</div>
<div class="clearfix"></div>
<?php endwhile; ?>
</div>
       <?php
    }
}
add_action('widgets_init', create_function('', 'return register_widget("PP_Widget");'));

サムネイル表示は、覚えた分岐を付け足してみました。 これで何も設定できないウィジェットの完成です 笑

完全に自分用覚書ですみません。

問題は、苦労し他にもかかわらず これ更新されてない気がするんだよね

いや正しくは、地味に更新されているんだけど、アクセスされてる記事とは違うよね・・・?っていう。

プラグイン使わないのも楽しいけどPHPわからないから時間だけが過ぎていく・・・ わかんねー 何か違うんだろうな〜 もういいやーってプラグイン使ったらいかんよねえ。 こっちもGA Ranking使うか、Jetpack絡みでいいのが無いか探そうかな

とりあえず、二つのサイトともPopularPostプラグイン使うのやめれました!!