我使用WordPress博客,我希望在不向数据库添加任何内容的情况下显示帖子。 我想说的是:
我在页面加载时生成一个帖子,并将其添加到主页中。
我搜索并找到wp_insert_post()
函数,但它也添加到数据库中。
我怎么能用PHP做到这一点?
例如: 有一个由查询生成的post数组。如何在页面加载之前将我的帖子插入此数组?
我想清楚我的想法。这就是我想要的一步一步。
* 1) *我正在生成这样的数组 $ arr ['title] =“我的头衔”, $ arr ['content'] =“我的内容”,
* 2) * WP向数据库发送查询,并且我的帖子是否合适?还有一个数组,在主题和主页上显示? 此时我想将我的外部数组(在步骤1中生成)添加到此数组(由WP通过查询生成)
3)通过这种方式,我可以在不将其添加到我的数据库的情况下添加帖子。
答案 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会导致新帖子删除循环中的最后一个帖子,因为它不会更新帖子计数。这是我的修改版本,其中还包括:
以下是修改后的代码:
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');
}