WordPress Popular Postsで「テーマのphpを変更せず」今見ている記事と同じカテゴリーの人気記事を表示する

Googleで「Wordpress Popular Posts カテゴリ」で検索すると、まさにやりたい事を解説している記事が多数見つけることができます。ただ期待していた方法ではなく、ほとんどがテーマのphpファイルに直接記述する方式でした。「functions.php」「footer.php」「single.php」にこういう風に記述しましょうと。

せっかくWordpress Popular Postsはウィジェット対応して、マウスで簡単に、かつ設定もチェックを入れたりするだけの超ユーザーフレンドリーなインターフェースが用意されているのに、これらをすべて捨ててまでテーマファイルに変更を加えるのにためらいを感じました。

テーマphpファイルに追加記述したWordpress Popular Postsの設定を変更するには、Wordpress Popular PostsのQ&A(要はヘルプみたいなもの)を見ながらコーディングするのも面倒だ。もう少し初心者でもできそうな方法はないものか。

 

 

ここからの記事は自己責任でお願いします。(php触ったことない人間が記事を書いているので正しいかどうか不明です。)

 

プラグイン側を変更する

テーマ側のphpをさわりたくないのなら、プラグイン側のphpをさわるしかありません。 (プラグイン側のphpを修正する方法などはぐぐってください。すいません。)

プラグイン側を変更するのですが、それでもwordpress-popular-posts/wordpress-popular-posts.phpはあまり変更したくありません。変更すべき箇所を関数化、別ファイル化しておきます。ファイルを追加するフォルダはwordpress-popular-posts/wordpress-popular-posts.phpと同じフォルダとします。(※プラグインが更新されるとフォルダごと消されてしまう?消されるようなら別の場所に入れましょう。)

新規で追加するwordpress-popular-posts/wordpress-popular-posts-ex.phpファイル。文字コードはUTF-8で保存し、FTPでサーバーにアップしましょう。

<?php
/*--------------------------------------------------*/
/* wordpress-popular-posts-ex.php
/*--------------------------------------------------*/
/**
 * 今見ている記事のカテゴリー人気記事になるように強制変換。
 * @author kikikotori
 */		
function _override_parameters( $instance, $post_id ) {
	// タイトルをカテゴリーに合わせて変更する
	$instance['title'] = _override_header_setting( $instance['title'], $post_id );

	// 表示カテゴリーを自動で指定する
	$instance['cat'] = _override_category_setting( $instance['cat'], $post_id );
	
	return $instance;
}

/**
 * 表示するカテゴリー設定を今の記事IDカテゴリーで上書きする。
 * @author kikikotori
 */		
function _override_category_setting( $now_cat_ids, $post_id ) {
	$new_cat_ids = '';
	/* single post, Same category as the article you are looking at now. */
	$categories = get_the_category();
	if( $categories && $post_id != 0 ) {
		$categories_id = array(count($categories));
		$categories_index = 0;
		foreach( $categories as $category ) {
			$categories_id[categories_index] = $category->cat_ID;
			$categories_index += 1;
		}
		$new_cat_ids = implode(",", $categories_id);
	}
	
	return $new_cat_ids;
}

/**
 * wordpress-popular-postsのタイトル文字を変更する。
 * @author kikikotori
 */		
function _override_header_setting( $title, $post_id ) {
	/* single post, Same category as the article you are looking at now. */
	$categories = get_the_category();
	if( $categories && $post_id != 0 ) {
		$categories_tags = array(count($categories));
		$categories_index = 0;
		$categories_name = '';
		foreach( $categories as $category ) {
			$categories_name .= '<a href="' . get_category_link( $category->term_id ) . '">' . $category->cat_name . '</a>';
		}
		$title = '「' . $categories_name . '」カテゴリーの人気記事';
	}
	return $title;
}


上のコードでは

  • 「表示している記事のカテゴリー名+αを、$instance[‘title’]にぶち込む」
  • 「表示している記事のカテゴリーID群を取得し、$instance[‘cat’]にぶち込む」

を行う2つの関数と、その関数をまとめたものの3つの関数から成ります。

2014.12.16追記 (説明とコードと関数名が微妙に合ってませんね。途中で修正したんだった・・・。)

あとトップページ的なところで記事のIDが無い場合は動作しないようにチェックしているだけです。(コードの美しさとかは気にしないでね。) トップページは全カテゴリーの人気記事が表示されるはず。

 

次にwordpress-popular-posts/wordpress-popular-posts.phpを修正します。修正時のプラグインバージョンは 3.2.1。

465行目から468行目までを追加。

			// has user set a title?
			if ( '' != $instance['title'] ) {
				$title = apply_filters( 'widget_title', $instance['title'] );
				
				// 今の記事に合わせたカテゴリー人気記事になるように、内部パラメータを書き換えます。
				require_once( 'wordpress-popular-posts-ex.php' );
				$title = _override_header_setting( $title, $this->current_post_id );

				if ($instance['markup']['custom_html'] && $instance['markup']['title-start'] != "" && $instance['markup']['title-end'] != "" ) {
					echo htmlspecialchars_decode($instance['markup']['title-start'], ENT_QUOTES) . $title . htmlspecialchars_decode($instance['markup']['title-end'], ENT_QUOTES);
				} else {
					echo $before_title . $title . $after_title;
				}
			}

1705行目から1707行目までを追加。

		/**
		 * Returns the formatted list of posts.
		 *
		 * @since	3.0.0
		 * @param	array	instance	The current instance of the widget / shortcode parameters
		 * @return	string	HTML list of popular posts
		 */
		private function __get_popular_posts( $instance ) {

			// Parse instance values
			$instance = $this->__merge_array_r(
				$this->defaults,
				$instance
			);

			// 今の記事に合わせたカテゴリー人気記事になるように、内部パラメータを書き換えます。
			require_once( 'wordpress-popular-posts-ex.php' );
			$instance['cat'] = _override_category_setting( $instance['cat'], $this->current_post_id );

			$content = "";

クエリ生成前に、さきほど追加した関数を呼び出し、表示するヘッダータイトル、表示するカテゴリーIDの2つを上書きしています。

 

この修正方法の良いところ

  • WordPress Popular Postsが用意してくれているユーザーインターフェースがそのまま使用できる。
  • 既に設置済みでも対応できる。

 

この修正方法の悪い

  • プラグインが更新されるたび、同じ作業で対応する必要がある。

 

まとめ

いかかでしょうか。wordpress-popular-posts.phpのいろいろな箇所に修正が入るわけではなく、2箇所の修正(本当は一箇所にしたかった)のお手軽な対応で気に入っています。既に配置済みの方でも、この適応方法ならphpだけの変更でOK。

ただ・・・、多分テーマ側で対応するのが正解だと思われますが、それじゃあ面白くない(!?)ので、この方法で試してみました。Wordpress Popular Postsが用意してくれているユーザーインターフェースがそのまま使用できる、というのが点のみがプラグイン側をいじる理由かもしれません。

本当の最初の目的だった「初心者でも簡単にできないの?」なんてどっかいっちゃった。この修正ができるなら、他の方法もできるよね。やっぱりプラグイン側で対応して、GUIで設定一発!ってのを望みますね。

 

実はまだある不満点

  • カテゴリーページでも全カテゴリーの人気記事が表示される

この点を簡単に解消できれば素敵ですね。(訳:プラグイン側で対応しないかな・・・)

 

WordPress Popular Postsプラグインのライセンス

ライセンスはGPLv2。あまりにもプラグイン側を変更する記事が無いのでライセンス的にNGなのか!?と焦った。

 

テーマファイルを変更する方法

この記事ではプラグイン側を修正しましたが、テーマ側を変更する方法として他サイト様の

WordPress Popular Postsの人気記事を、今見ている記事と同じカテゴリーのものを表示する方法

WordPress Popular Postsで、現在とそれ以外のカテゴリの人気記事をそれぞれ表示する

などの記事が参考になります。他の方法も検討するとよいですよ。


希木小鳥

Diablo1でハクスラの世界に。今はBorderlands2をプレイ中。ぬるゲーマー。

あわせて読みたい