WordPress

アクセス数をカウントする

'15.10.18

functions.phpに以下を追記。

//アクセスBotの判断
function isBot() {
  $bot_list = array (
    'Googlebot',
    'Yahoo! Slurp',
    'Mediapartners-Google',
    'msnbot',
    'bingbot',
    'MJ12bot',
    'Ezooms',
    'pirst; MSIE 8.0;',
    'Google Web Preview',
    'ia_archiver',
    'Sogou web spider',
    'Googlebot-Mobile',
    'AhrefsBot',
    'YandexBot',
    'Purebot',
    'Baiduspider',
    'UnwindFetchor',
    'TweetmemeBot',
    'MetaURI',
    'PaperLiBot',
    'Showyoubot',
    'JS-Kit',
    'PostRank',
    'Crowsnest',
    'PycURL',
    'bitlybot',
    'Hatena',
    'facebookexternalhit',
    'NINJA bot',
    'YahooCacheSystem',
  );

  $is_bot = false;
  foreach ($bot_list as $bot) {
    if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false) {
      $is_bot = true;
      break;
    }
  }
  return $is_bot;
}
//アクセス数の取得
function get_post_views( $postID ) {
    $count_key = 'post_views_count';
    $count     = get_post_meta( $postID, $count_key, true );
    if ( $count == '' ) {
        delete_post_meta( $postID, $count_key );
        add_post_meta( $postID, $count_key, '0' );

        return "0 views";
    }

    return $count . '';
}

//アクセス数の保存
function set_post_views( $postID ) {
    $count_key = 'post_views_count';
    $count     = get_post_meta( $postID, $count_key, true );
    if ( $count == '' ) {
        $count = 0;
        delete_post_meta( $postID, $count_key );
        add_post_meta( $postID, $count_key, '0' );
    } else {
        $count ++;
        update_post_meta( $postID, $count_key, $count );
    }
}

 

単一ページに下記を挿入(閲覧後カウントを増やす)

<?php echo get_post_views(get_the_ID()); ?> <?php if(!is_user_logged_in()){set_post_views(get_the_ID());} ?>

一覧などには下記を挿入(カウントを増やさない)

<?php echo get_post_views(get_the_ID()); ?>

 

(View114)