如何注入虚拟帖子(即不将其添加到数据库)

时间:2013-01-22 13:39:59

标签: php wordpress post

我使用WordPress博客,我希望在不向数据库添加任何内容的情况下显示帖子。 我想说的是:

我在页面加载时生成一个帖子,并将其添加到主页中。 我搜索并找到wp_insert_post()函数,但它也添加到数据库中。 我怎么能用PHP做到这一点?

例如: 有一个由查询生成的post数组。如何在页面加载之前将我的帖子插入此数组?

我想清楚我的想法。这就是我想要的一步一步。

* 1) *我正在生成这样的数组 $ arr ['title] =“我的头衔”, $ arr ['content'] =“我的内容”,

* 2) * WP向数据库发送查询,并且我的帖子是否合适?还有一个数组,在主题和主页上显示? 此时我想将我的外部数组(在步骤1中生成)添加到此数组(由WP通过查询生成)

3)通过这种方式,我可以在不将其添加到我的数据库的情况下添加帖子。

2 个答案:

答案 0 :(得分:2)

您只需在主题模板中添加虚拟帖子作为原始HTML。

或者,如果您喜欢冒险,可以修改主要查询结果并将帖子包含在内:

add_action('loop_start', function($query){

  // create the post and fill up the fields
  $post = new WP_Post((object)array(
    'ID'           => -1,
    'post_title'   => 'Bla blah',
    'post_content' => 'Your content',
  ));

  // add it to the internal cache, so WP doesn't fire a database query for it
  // -1 is the ID of your post
  if(!wp_cache_get(-1, 'posts'))
    wp_cache_set(-1, $post, 'posts');

  // prepend it to the query
  array_unshift($query->posts, $post);
});

答案 1 :(得分:1)

The currently accepted answer会导致新帖子删除循环中的最后一个帖子,因为它不会更新帖子计数。这是我的修改版本,其中还包括:

  1. 支持空类别。
  2. 只有一个地方可以宣布新帖子的ID。
  3. 将is_main_query()添加为评论中提到的最初回答的人。
  4. 用于决定是否应追加或添加新帖子的设置。
  5. 隐藏帖子的日期,因为否则你会得到像00000000这样的东西。我本可以使用动态日期但是在不更新内容的情况下不断更新日期可能是不好的。
  6. 隐藏帖子的评论链接,因为它只是指向主页。
  7. 用于控制帖子类型的设置。您可能更喜欢“page”,因为“post”会显示一般类别,我发现无法绕过。假设这是一件好事,“Page”在其他帖子中看起来也更加突出。
  8. 以下是修改后的代码:

    function virtual_post($query) {
      $post_type = 'page'; // default is post
      if (get_class($query)=='WP')
         $query = $GLOBALS['wp_query'];
      if ($query->is_main_query()) {
         $append = true; // or prepend
         // create the post and fill up the fields
         $post = new WP_Post((object)array(
          'ID'           => -1,
          'post_title'   => 'Dummy post',
          'post_content' => 'This is a fake virtual post.',
          'post_date' => '',
          'comment_status' => 'closed'
         ));
         if ($post_type <> 'post')
           $post->post_type = $post_type;
         // add it to the internal cache, so WP doesn't fire a database query for it
         if(!wp_cache_get($post->ID, 'posts')) {
           wp_cache_set($post->ID, $post, 'posts');
           if ($query->post_count==0 || $append)
             $query->posts[] = $post;
           else
             array_unshift($query->posts, $post);
           $query->post_count++;
         }
      }
    }
    
    $virtual_post_settings = array('enable' => true, 'include_empty_categories' => true);
    if ($virtual_post_settings['enable']) {
      if ($virtual_post_settings['include_empty_categories'])
        add_action('wp', 'virtual_post');
      else
        add_action('loop_start', 'virtual_post');
    }