0

我有一个WordPress网站和一个显示所有 WordPress 帖子的页面。现在我每分钟刷新一次页面javascript。但这有点烦人,因为我希望它只在wp_postsorwp_postmeta表中有更新时刷新。有没有可以在更新时调用的功能post

我读过一些关于save_post. https://developer.wordpress.org/reference/hooks/save_post/

但这仅在后端保存后运行。我想在管理员在后端更新帖子后在前端运行此功能,以便我可以在前端的此功能内运行页面重新加载。

也许还有另一个功能?

编辑:

在我让一切正常工作之前,我想知道为什么这不起作用:

$(document).ready(function() {

window.setInterval(function(){
    <?php
    global $wpdb;
    $sql = "SELECT * FROM `wp_posts` ORDER BY post_modified DESC LIMIT 1";
    $resultaten = $wpdb->get_results($sql);

    foreach ($resultaten as $resultaat) {
        $datumtijd = $resultaat->post_modified;
        $datum_en_tijd = date("d-m-Y H:i", strtotime($datumtijd)); ?>

        console.log("<?php echo $datum_en_tijd; ?>");
    <?php } ?> 
                
},10000);
});

这工作正常,每 10 秒记录一次,但每次我在后端更新帖子时,它都会返回相同的结果。但是,如果我在其中使用查询,phpMyAdmin每次都会返回不同的值,所以看起来查询不会再次运行?

4

1 回答 1

0

只是勾勒出它是怎么回事。

// PHP ( functions.php )
// save updating timestamp to options
add_action('save_post', function(){
    if( DOING_AUTOSAVE )
        return;

    // maybe some filters here to setup updating only on specific post types & other cond.

    update_option( 'last_post_update', time(), true );
});
add_action('wp_ajax_check_post_updates', function(){
    do_action('wp_ajax_nopriv_check_post_updates');
});
add_action('wp_ajax_nopriv_check_post_updates', function(){
    $last_update = get_option('last_post_update', time());
    $last_updated = (int) $_POST['last_updated'];

    // no new posts / updates
    if( $last_update <= $last_updated )
        return;

    // get posts based on your options and return html 
});

和前端

// JS
let last_updated = $('#pageWasLoadedAt').val(); // print hidden input somewhere with time() when page was loaded

setInterval(() => {
    const $container = $('#container-with-posts');
    $.ajax({
        dataType: 'html',
        data :{
            action: 'last_updated',
            last_updated: last_updated
        },
        complete: function(){ last_updated = Date.now(); },
        success:function(response){
            if( response ) $container.html(response);
        }
    });
于 2020-06-24T09:25:52.137 回答