WordPressで、更新履歴やお知らせ履歴をリスト表示したシンプルな別ページを作って、トップページやサイドバーからiFrameやphpのinclude等で呼び出したいケースがあります。
方法は色々ありそうです。私がクライアントさんのサイトで行った方法を紹介します。少々強引です。私が実施した方法は、固定ページ内に更新履歴やお知らせ履歴のループをPHPで書いてしまう方法です。Exec-PHPプラグインを利用すれば、固定ページ内でPHPを実行することができます。
色々、最悪です。
まず、顧客案件で Exec-PHP を使うなんてもってのほか。
例えば、お客さんが以下のようなコードを通常記事に打ったら、MySQL のユーザーアカウント/パスワードが漏洩してしまいます。
<?php
echo DB_USER ."\n";
echo DB_PASSWORD."\n";
?>
まぁ、これは極端な例ですが…
Exec-PHP を入れているサイトの投稿者アカウント(管理者権限が無いアカウントでも!)が漏れてしまった場合、攻撃者は好きなだけサーバ上で php コードを実行できるので非常に危険です。
このプラグインを使うのはやめましょう。
あと、メインクエリーの中で query_posts() 使うなとか色々言いたいことはありますが…
この案件の場合はショートコードを用意してやるのが良いです。こんな感じ。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_shortcode('recent_posts', 'my_recent_posts'); | |
function my_recent_posts($atts) { | |
// デフォルトテンプレート | |
$template = '<div style="border-bottom:dotted 1px #aaaaaa;margin-bottom:20px;font-size:14px"> | |
<div class="title"><a href="%s" target="_top">%s</a></div> | |
<div class="day" style="font-size:12px;color:#999999">%s</div> | |
</div> | |
'; | |
// 引数の処理 | |
extract(shortcode_atts(array( | |
'template' => $template, | |
'args' => 'post_type=post&posts_per_page=10', | |
), $atts)); | |
$the_list = ''; | |
// 最新のポスト取得 | |
$posts = get_posts($args); | |
foreach ($posts as $post) { | |
$the_list .= sprintf( | |
$template, | |
esc_attr(get_permalink($post->ID)), | |
esc_html($post->post_title), | |
mysql2date("Y年m月j日", $post->post_date) | |
); | |
} | |
return $the_list; | |
} |
これで、固定ページ中に [recent_posts] ってショートコードを書いてやれば表示できるようになります。
追記:
もしくは、テーマテンプレート内にウィジェットエリアを用意して「最近の投稿」ウィジェットを使っても良いねって指摘もありました。
そっちの方が簡単かもですね。やりやすいほうで。
追記2:
似たようなことをやるプラグインもあるそうです。
コメントを残す