Wordpress - 在页面和帖子之外使用评论系统

cho*_*ise 4 php wordpress comments podscms

所以目前我正在使用pods为日志创建一些单独的页面,其中包含自定义内容.

现在我想为每个页面使用评论系统,例如:

mydomain.com/podpages/page1
mydomain.com/podpages/page2
mydomain.com/podpages/page3
Run Code Online (Sandbox Code Playgroud)

不是使用wordpress创建的页面,因此简单地添加<?php comments_template(); ?>不起作用.

任何想法如何解决这个问题?提前致谢

如果有什么不清楚请发表评论:)

The*_*dic 11

当评论存储在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       
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

我简直不敢相信我这是愚蠢的.下面应该替换外部的当前代码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(); 
Run Code Online (Sandbox Code Playgroud)

PS我想用query_var namepagename更适合-它查询蛞蝓,而不是塞"路径".

您还需要在表单中放置一个带有名称的输入redirect_to和要重定向到的URL的值,或者使用挂钩的函数过滤重定向comment_post_redirect,返回正确的URL.