コメントがWordPressデータベースに保存されると、コメントに関連する投稿(またはページ)のIDも保存されます。
問題は、WordPressを使用してコメントを保存しようとしているのに、実際には知らないページの場合です。
では、実際のページごとにWordPressページを作成するのはどうでしょうか。ただし、実際のページとWordPressが相互に連携するための共通の基盤を持つように、単なる表現として作成します。
したがって、ここでの計画は次のとおりです。
- 「実際の」各ページのバックグラウンドでWordPressをロードします。
- 「実際の」ページにWordPressページ表現がすでに存在するかどうかを確認します
- そうでない場合は、それを作成し、その場で作成します
- WordPressをだまして、実際に表現を見ていると思い込ませます
- 通常どおり、WPのすべての関数と「テンプレートタグ」を引き続き使用します
このコードは、「実際の」ページのレンダリングに使用されるテンプレートファイルの先頭のどこかにある必要があります。
include ('../path/to/wp-load.php');
// remove query string from request
$request = preg_replace('#\?.*$#', '', $_SERVER['REQUEST_URI']);
// try and get the page name from the URI
preg_match('#podpages/([a-z0-9_-]+)#', $matches);
if ($matches && isset($matches[1])) {
$pagename = $matches[1];
// try and find the WP representation page
$query = new WP_Query(array('pagename' => $pagename));
if (!$query->have_posts()) {
// no WP page exists yet, so create one
$id = wp_insert_post(array(
'post_title' => $pagename,
'post_type' => 'page',
'post_status' => 'publish',
'post_name' => $pagename
));
if (!$id)
do_something(); // something went wrong
}
// this sets up the main WordPress query
// from now on, WordPress thinks you're viewing the representation page
}
アップデート
こんなにバカだったなんて信じられない。以下は、outer内の現在のコードを置き換える必要がありif
ます。
// try and find the WP representation page - post_type IS required
$query = new WP_Query(array('name' => $pagename, 'post_type' => 'page'));
if (!$query->have_posts()) {
// no WP page exists yet, so create one
$id = wp_insert_post(array(
'post_title' => $pagename,
'post_type' => 'page',
'post_status' => 'publish',
'post_name' => $pagename,
'post_author' => 1, // failsafe
'post_content' => 'wp_insert_post needs content to complete'
));
}
// this sets up the main WordPress query
// from now on, WordPress thinks you're viewing the representation page
// post_type is a must!
wp(array('name' => $pagename, 'post_type' => 'page'));
// set up post
the_post();
PS query_var name
overを使用するpagename
方が適していると思います。これは、スラッグの「パス」ではなく、スラッグを照会します。
また、リダイレクト先の名前redirect_to
とURLの値を使用してフォーム内に入力を配置するか、にフックされた関数でリダイレクトをフィルタリングしてcomment_post_redirect
、正しいURLを返す必要があります。