我正在尝试在WordPress搜索结果中插入一些虚假帖子。使用pre_get_posts挂钩,我可以触发该函数,但无法将假帖子添加到WordPress结果中。
我关注了另一篇有关插入假帖子的帖子。文章提到将伪造的帖子插入wp-cache。
任何帮助将不胜感激。
function extra_search_items($query) {
if ($query->is_search && !is_admin()) {
global $wp, $wp_query;
$FakePosts = array(
array(
'ID' => -199,
'post_title' => 'Fake 1',
'post_content' => 'This is a fake virtual post.',
'post_date' => '2018-06-22 00:00:00',
'comment_status' => 'closed',
'post_type' => 'post'
),
array(
'ID' => -200,
'post_title' => 'Fake 2',
'post_content' => 'This is a fake virtual post.',
'post_date' => '2018-06-22 00:00:00',
'comment_status' => 'closed',
'post_type' => 'post'
)
);
$i = 0;
$post = array();
foreach ($FakePosts as $blog) {
// create the post and fill up the fields
$post[$i] = new WP_Post((object)array(
'ID' => $blog['ID'],
'post_title' => $blog['post_title'],
'post_content' => $blog['post_content'],
'post_date' => $blog['post_date'],
'comment_status' => $blog['comment_status'],
'post_type' => $blog['post_type']
));
if(!wp_cache_get($post[$i]->ID, 'posts')) {
wp_cache_set($post[$i]->ID, $post[$i], 'posts');
array_unshift($wp_query->posts, $post[$i]);
$wp_query->post_count++;
}
$i++;
}
}
return $wp_query;
}
add_action('pre_get_posts','extra_search_items');
答案 0 :(得分:0)
您创建了假帖子数组,但没有将假帖子与原始帖子组合在一起。
合并两个数组并循环,然后它也会显示假帖子,
类似于以下内容
function extra_search_items($query) {
if ($query->is_search && !is_admin()) {
global $wp, $wp_query;
$FakePosts1 = array(
array(
'ID' => -199,
'post_title' => 'Fake 1',
'post_content' => 'This is a fake virtual post.',
'post_date' => '2018-06-22 00:00:00',
'comment_status' => 'closed',
'post_type' => 'post'
),
array(
'ID' => -200,
'post_title' => 'Fake 2',
'post_content' => 'This is a fake virtual post.',
'post_date' => '2018-06-22 00:00:00',
'comment_status' => 'closed',
'post_type' => 'post'
)
);
$i = 0;
$post = array();
$FakePosts_array = array_merge($FakePosts1,$FakePosts)
foreach ($FakePosts_array as $blog) {
// create the post and fill up the fields
$post[$i] = new WP_Post((object)array(
'ID' => $blog['ID'],
'post_title' => $blog['post_title'],
'post_content' => $blog['post_content'],
'post_date' => $blog['post_date'],
'comment_status' => $blog['comment_status'],
'post_type' => $blog['post_type']
));
if(!wp_cache_get($post[$i]->ID, 'posts')) {
wp_cache_set($post[$i]->ID, $post[$i], 'posts');
array_unshift($wp_query->posts, $post[$i]);
$wp_query->post_count++;
}
$i++;
}
}
return $wp_query;
}
add_action('pre_get_posts','extra_search_items');