小金井にあるWEB制作会社の備忘録

MEMORANDUM

WordPress(ワードプレス)で複数のデーターベースの内容を読み込む。

WordPress(ワードプレス)を使ってサイトを作る際に、既に別サイト(同一サーバー内)で作成しているコンテンツなどを共有して制作したい場合(本サイトとは別のデータベースを読み込みたい場合)の対応方法をメモ。

function.php(PHP)

//他のデータベースに接続
$another_db_user = 'データーベースユーザー名';
$another_db_pass = 'データーベースパスワード';
$another_db_name = 'データーベース名';
$another_db_host = 'データーベースホスト名';
$another_tb_prefix = 'wp○○_';

$another_wpdb = new wpdb($another_db_user, $another_db_pass, $another_db_name, $another_db_host);
$another_wpdb->set_prefix($another_tb_prefix);

読み込みページ(PHP)

こちらのサンプルでは追加で読み込むデータベースもワードプレスを使用し、投稿一覧の内容を表示しています。

/*
Template Name: 読み込みに使用するページのテンプレート名
*/

//SQLでデーターベースに直接アクセスして、情報をとる
$result = $another_wpdb->get_results('
	SELECT * FROM '.$another_wpdb->posts.'
	WHERE post_type = "post"
	&& post_status = "publish"
	ORDER BY post_date DESC
');
foreach ($result as $value) {
	$the_post_id = $value->ID; // カテゴリとアイキャッチを取得したい投稿のID
	
	//カテゴリーの取得
	$categories = '';
	$get_term_relationships_res = $another_wpdb->get_results('SELECT '.$another_wpdb->term_relationships.'.term_taxonomy_id as term_taxonomy_id FROM '.$another_wpdb->term_relationships.', '.$another_wpdb->term_taxonomy.' WHERE '.$another_wpdb->term_relationships.'.term_taxonomy_id = '.$another_wpdb->term_taxonomy.'.term_taxonomy_id && '.$another_wpdb->term_relationships.'.object_id = "'.$the_post_id.'" && '.$another_wpdb->term_taxonomy.'.taxonomy = "category"');
	foreach($get_term_relationships_res as $row_term_relationships){
		$get_terms_res = $another_wpdb->get_results('SELECT name FROM '.$another_wpdb->terms.' WHERE term_id = "'.$row_term_relationships->term_taxonomy_id.'"');
		foreach($get_terms_res as $row_terms){
			$categories .= $row_terms->name;
		}
	}

	//アイキャッチの取得
	$get_postmeta_res = $another_wpdb->get_results('SELECT meta_value FROM '.$another_wpdb->postmeta.' WHERE meta_key = "_thumbnail_id" && post_id = "'.$the_post_id.'"');
	foreach ($get_postmeta_res as $row_get_postmeta ) {
		$get_attachment_res = $another_wpdb->get_results('SELECT * FROM '.$another_wpdb->posts.' WHERE post_type = "attachment" && ID="'.$row_get_postmeta->meta_value.'"');
		foreach($get_attachment_res as $row_get_attachment){
			$eyecatch = $row_get_attachment->guid;
		}
	}
		
	//表示内容
	echo('<li class="post">
	<span class="cat-name">'.$categories.'</span>
	<a href="'.$value->ID.'">
	<figure class="eyecatch"><img src="'.$eyecatch.'"></figure>
	<div class="entry-content">
	<h2 class="entry-title">'.$value->post_title.'</h2>
	<p class="entry-meta">'.$value->post_date.'</p>
	<p class="description">'.mb_substr(strip_tags($value->post_content), 0, 50, 'UTF-8').'</p>
	</div>
	</a>
	</li>');
}

同一カテゴリーの記事