2015.12.24
人気記事をランキング表示するプラグイン「WordPress Popular Posts」
WordPress Popular Postsは、閲覧数などを取得して記事をランキング表示するプラグインです。
ブログ形式のWebサイトでサイドバーなどに導入されているのをよくみかけますね。
ウィジェットを利用して追加することも可能ですが、今回はテーマファイルに直接記入してカスタマイズする方法をご紹介します。
ダウンロード
設定
プラグインをダウンロードし有効化後、「設定」→「WordPress Popular Posts」の「Tool」タブから設定を行います。
カスタマイズして表示する場合、基本的にはそのままでも問題はありませんが、ランキングデータの取得方法などを変更する場合は、こちらで設定する必要があります。
出力
今回はタイトルや投稿日時など、記事の基本データを取得して表示させるようにしました。
functions.phpにて情報を取得し、HTMLタグを含めた出力形式を指定しておき、テンプレートファイル側でその内容を出力しています。
カスタマイズ例:functions.php
$GLOBALS["ranking_count"] = 1; function my_popular_post( $post_html, $p, $instance ){ // 投稿IDの取得 $post_id = $p->id; // 投稿日時 $date = get_the_date('Y.m.d',$post_id); // タイトル $title = get_the_title($post_id); // パーマリンク $permalink = get_the_permalink($post_id); // 画像(Advanced Custom Fieldsを使用) if ( get_field('post_image',$post_id) ) { $image = get_field('post_image',$post_id); } else { $image = get_bloginfo('template_url') . '/images/image_blank.png'; } // ポストタイプ名 $posts = get_post($post_id); $postType = $posts->post_type; $postTypeLabel = get_post_type_object( $postType )->label; // ターム名 $terms = get_the_terms($post_id,'POST_TYPE_NAME'); foreach ( $terms as $term ) { $termName = $term->name; }; // ランキング $ranking = $GLOBALS["ranking_count"]++; // 出力 echo <<< EOF 投稿日時:{$date} タイトル:{$title} パーマリンク:{$permalink} 画像:{$image} ポストタイプ名:{$postTypeLabel} ターム名:{$termName} ランキング順:{$ranking} EOF; } add_filter( 'wpp_post', 'my_popular_post', 10, 3 );
カスタマイズ例:テンプレートファイル(index.php / sidebar.php など)
<!--?php if (function_exists('wpp_get_mostpopular')) { $arg = array ( 'post_type' => 'post', // 投稿のタイプを指定<br ?--> // 'post_type' => 'POST_TYPE_NAME,POST_TYPE_NAME', 複数の投稿タイプ指定の場合 'range' => 'all', // 集計期間 'daily', 'weekly', 'monthly', 'all' 'order_by' => 'views', // 表示順 'comments', 'avg' 'limit' => 4 // 表示投稿数 ); wpp_get_mostpopular($arg); } ?>