LinkStory Wiki
【WP】プラグインなしで人気の記事一覧を表示したい
function.phpに記述!
singleページの閲覧回数をカウントします。
// singleページの記事閲覧回数カウント関数
function popular_posts_ranking() {
if (!is_single()) return;
if (empty($post_id)) {
global $post;
$post_id = $post->ID;
}
session_start();
if (!isset($_SESSION['custom_popular_id_'.$post_id])) {
$_SESSION['custom_popular_id_'.$post_id] = 1;
$custom_key = 'custom_popular_ranking';
$cnt = get_post_meta($post_id, $custom_key, true);
if ($cnt == '') {
$cnt = 1;
add_post_meta($post_id, $custom_key, $cnt);
} else {
$cnt++;
update_post_meta($post_id, $custom_key, $cnt);
}
}
session_write_close();
}
add_action('wp_head', 'popular_posts_ranking');
閲覧回数順に表示したい場合は、以下を表示したいページのループにオプションで設定。
$custom_key = 'custom_popular_ranking';
$args = array(
'post_type' => array( 'interviews', 'post' ),
'posts_per_page'=>3,
'meta_key'=>$custom_key,
'orderby'=>'meta_value_num',
'order'=>'DESC'
);