当评论存储在 WordPress 数据库中时,评论相关的帖子(或页面)的 ID 也会被存储。
问题是,您正在尝试使用 WordPress 保存 cmets,但是对于一个它实际上并不知道的页面。
那么,我们如何为每个真实页面创建一个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
}
更新
我不敢相信我这么愚蠢。下面应该替换外部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();
P.S 我认为使用 query_var name 而不是 pagename 更适合 - 它查询 slug,而不是 slug 的“路径”。
您还需要在表单中输入名称为 redirect_to 的输入和您要重定向到的 URL 的值,或,使用函数过滤重定向连接到comment_post_redirect,返回正确的 URL。