在主页上实时显示帖子(一旦发布)



我注意到这已经成为评论和现在的帖子的趋势。我相信很多网站(尤其是社区网站)会实现这个。

这就是我的意思,点击这里:https://stackexchange.com/questions?tab=realtime

帖子一经发布就会实时显示。

还有另一个版本,其中扩展链接显示(1个问题与新活动)。如果等待几秒钟,您可以在这里看到它的实际效果:https://superuser.com/

我想知道有没有办法在Wordpress上做到这一点?用我的循环?

现在我的循环是这样的:

<?php 
// Limit query posts to the current day
// 
$period = $_GET["period"];
$day = $_GET["d"];
$year = $_GET["y"]; 
$args = array(
'year' => (int) date($year),    
'monthnum' => (int) date( 'M' ),    
'day' => (int) date($day), 
'date_query' => array(
array(
'after' => ($period), 
)
)

);
$query = new WP_Query( $args );
// The Loop
while ( $query->have_posts() ) :
$query->the_post();

get_template_part( 'template-parts/content', get_post_type() );

endwhile;
the_posts_navigation();
?>

我想这会帮助很多人。谢谢。

有很多方法可以做到这一点,你可以使用WebSockets(这是最好的选择)发送一个事件给每个客户端,当一个新的帖子,他们会更新页面上的HTML。

另一个选择是使用AJAX实现(不是最好的选择,但更简单)。基本上,它将每X次发送一个请求,以检查是否有上次请求的更新。如果有新的帖子,用内容更新HTML。我将在下面说明为什么这不是最好的选择。

通过websocket

WebSockets是一个巨大的领域(支持图表),你应该搜索一些文章来了解它们是如何实现你自己的逻辑的。一个非常简单的例子将使用Ratchet库来制作PHP部分和Socket。

可以使用wp_insert_post钩子在每次插入新帖子时向所有客户端发送包含帖子详细信息的消息:

function send_new_post( $post_id, $post, $update ) {
foreach ($clients as $client) {
// Sending title and url to each client connected
$client->send(json_encode(array('title' => $post->post_title, 'url' => get_permalink( $post_id ))));
}
}
add_action( 'wp_insert_post', 'send_new_post', 10, 3 );

看一下使用棘轮的示例聊天实现。

通过AJAX

首先,我不建议在有很多(甚至不是很多)客户机的站点上使用AJAX来完成此操作,因为您很容易使服务器每隔X秒就发出这些请求。

let timestamp = 0;
function get_updates(){
let url = '?real_time=' + timestamp;
let update = $.ajax({
type: 'POST',
url: url,
async: false,
dataType: 'json',
}).complete(function(data){
// Get the current timestamp to make the next call
timestamp = data.timestamp;
if (data.posts){
$.each(data.posts, function(index, element) {
$('.posts').append($('<div>', {
text: element.title
}));
});
}
setTimeout(function(){get_updates();}, 10000); // 30 seconds
});
}
get_updates();

时间戳将在第一次调用时同步,以防止不同时区的客户端获得不同的时间戳,防止旧的帖子被显示两次。

下面是返回帖子的一个基本示例。您可能应该对时间戳进行一些额外的验证,以防止显示非常旧的帖子,甚至添加posts_per_page以不显示很多帖子,从而给您的服务器造成很大的压力:
function get_real_time_posts(){
if (!isset($_GET['real_time'])){
return;
}
// Check if it is a valid timestamp
if ( !((string) (int) $_GET['real_time'] === $_GET['real_time']) 
|| !($_GET['real_time'] <= PHP_INT_MAX)
|| !($_GET['real_time'] >= ~PHP_INT_MAX)) {
return;
}
$time = intval($_GET['real_time']);

if ($time == 0) {
// First call to sync timestamps
echo json_encode(array(
'posts' => [],
'timestamp' => time()
));
die;
}
$args = array(
'post_type' => 'post',
'date_query' => array(
'after' => date('Y-m-d H:i:s', $time)
)
);
$query = new WP_Query( $args );
$posts = array();
foreach ($query->posts as $key => $value) {
$post = array(
'ID' => $value->ID,
'title' => $value->post_title,
'excerpt' => $value->post_excerpt
);
$posts[] = $post;
}
$result = array(
'posts' => $posts,
'timestamp' => time()
);
echo json_encode($result);
die;
}

最新更新