', '>' . PHP_EOL, $html);
// OGPを差し込む
$ogp = get_ogp();
if ( $ogp ) {
$from = '';
$to = $ogp;
$html = str_replace($from, $to, $html);
}
echo $html;
} catch (Exception $e) {
echo $html;
//echo '';
}
function get_ogp()
{
// URLを解析
if ( !isset($_SERVER['REQUEST_URI']) ) {
return '';
}
$uri = $_SERVER['REQUEST_URI'];
if ( preg_match('|/s/([0-9]+)/|', $uri, $matches) ) {
$post_id = $matches[1];
if ( !$post_id ) {
return '';
}
$pdo = get_pdo();
if ( !$pdo ) {
return '';
}
// URLのベース部分
// 本番系のものを使う
//$base_url = 'https://' . $_SERVER['SERVER_NAME'];
$base_url = 'https://www.technologyreview.jp';
// 英語記事タイトルと抜粋を取得
$sql = 'SELECT post_title, post_excerpt FROM wp_2_posts WHERE ID = :id';
$sth = $pdo->prepare($sql);
$sth->bindValue('id', $post_id);
$sth->execute();
$rows = $sth->fetch(PDO::FETCH_NUM);
// 英語記事タイトルからslugを作成
$slug = $rows[0];
$slug = strtolower($slug);
$slug = preg_replace('/[^a-z0-9 ]/', '', $slug);
$slug = str_replace(' ', '-', $slug);
// 記事URLを生成
$url = sprintf('%s/s/%d/%s/', $base_url, $post_id, $slug);
// 抜粋
$description = $rows[1];
// 日本語記事タイトルを取得
$sql = 'SELECT meta_value FROM wp_2_postmeta WHERE post_id = :id AND meta_key = :meta_key';
$sth = $pdo->prepare($sql);
$sth->bindValue('id', $post_id);
$sth->bindValue('meta_key', 'article_title');
$sth->execute();
// 日本語タイトル
$title = $sth->fetchColumn();
// サムネイル画像の情報を取得
$ogp_image = '';
//$sql = 'SELECT meta_value FROM wp_2_postmeta WHERE post_id = :id AND meta_key = :meta_key';
//$sth = $pdo->prepare($sql);
//$sth->bindValue('id', $post_id);
$sth->bindValue('meta_key', '_thumbnail_id');
$sth->execute();
// サムネイル画像の投稿ID
$thumbnail_id = $sth->fetchColumn();
//echo '';
if ( $thumbnail_id ) {
// 画像の状態データを取得
//$sql = 'SELECT meta_value FROM wp_2_postmeta WHERE post_id = :id AND meta_key = :meta_key';
//$sth = $pdo->prepare($sql);
$sth->bindValue('id', $thumbnail_id);
$sth->bindValue('meta_key', '_wp_attachment_metadata');
$sth->execute();
$metadata = $sth->fetchColumn();
//echo '';
$metadata = unserialize($metadata);
//echo '';
if ( isset($metadata['sizes']['thumb_1400']) ) {
$image_base = $metadata['file'];
$image_file = $metadata['sizes']['thumb_1400']['file'];
$image_width = $metadata['sizes']['thumb_1400']['width'];
$image_height = $metadata['sizes']['thumb_1400']['height'];
$image_url = sprintf('%s/wp-content/uploads/sites/2/%s/%s', $base_url, dirname($image_base), $image_file);
$ogp_image = <<
EOT;
}
}
return <<
$ogp_image
EOT;
}
return '';
}
function get_pdo()
{
$pdo = new PDO(DB_DSN, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}