【问题标题】:Refresh changes and new posts in wp query using ajax使用 ajax 刷新 wp 查询中的更改和新帖子
【发布时间】:2020-08-26 06:51:54
【问题描述】:

我正在尝试在 wordpress 上创建一个页面,所有新帖子和现有帖子的更改都会自动显示在提要中。提要每 5 秒重新加载一次。

在下面的代码中,我只从数据库中获取了记录,并且每 5 秒所有帖子将在最后再次添加。

在上次从数据库中“获取”后,如何检查帖子是新帖子还是更改?

display.php

<?php include( '../../../../wp-load.php' ); // loads WordPress Environment ?>
<?php
$fivesdrafts = $wpdb->get_results( 
    "
    SELECT ID, post_title 
    FROM $wpdb->posts
    WHERE post_type = 'post' "
);

foreach ( $fivesdrafts as $fivesdraft ) 
{
    echo $fivesdraft->post_title;
}

?>

single.php

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(ajaxCall, 5000);

function ajaxCall() {
    $.ajax({
            url: 'http://localhost:8888/wp-content/themes/wp-bootstrap-starter/inc/display.php',
            success: function(data) {

                $('p').append(data);
            }
        });
}

</script>

        <section id="primary" class="content-area col-sm-12 col-lg-12">
            <main id="main" class="site-main" role="main">

                <p></p>

            </main><!-- #main -->
        </section><!-- #primary -->

【问题讨论】:

  • 所以您只想显示最近 5 秒内更新的帖子?例如,如果在该时间间隔内只更新了一篇文章,是否只显示该文章?或者您想显示最近更新的帖子,无论它们是否在过去 5 秒内更新?
  • 不,我想显示所有帖子,但是当内容被编辑后,它会自动更改而无需重新加载页面。新帖子也会出现。但我找到了一个解决方案 - 见下文。

标签: jquery mysql wordpress


【解决方案1】:

下面的代码对我有用:

<script type="text/javascript">
setInterval("my_function();",3000); // Reload every 3 sec.
function my_function(){
    $('#package_list').load(location.href + ' #package_list'); // Reload content in #package_list div
}
</script>

带有 wordpress 查询的 div 位于 &lt;div id="package_list"&gt;&lt;/div&gt; 内,并自动获取所有更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多