检查wp\u posts或wp\u postemta表中的更新

zujrkrfu  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(224)

我有一个 WordPress 网站,并有一个网页,显示所有的wordpress职位。现在我每分钟都用 javascript . 但这是一种恼人的,因为我只希望它刷新时,有一个更新中 wp_posts 或者 wp_postmeta table。有一个函数我可以在 post 更新?
我读到一些关于 save_post . https://developer.wordpress.org/reference/hooks/save_post/
但这只在后端post save上运行。我想在管理员更新后端中的文章后在前端运行此函数,这样我就可以在前端运行此函数中的页面重新加载。
也许还有别的功能?
编辑:
在一切正常工作之前,我想知道为什么这不起作用:

$(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 它每次都返回一个不同的值,这样看起来查询不会再次运行了?

0pizxfdo

0pizxfdo1#

只是简单地描述一下。

// 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);
        }
    });

相关问题